Solve ax + by = C equations like this

Source: Internet
Author: User

Basic knowledge:

1. For any ax+by=c, if we know there is a group of solutions x0, y0; Then x1 = x0+kb ' (b ' =b/gcd (A, a)), y1 = Y0-ka ' (a ' =a/gcd (b));

The process for solving ax + by = C is as follows:

1. First we use EGCD to find the solution of ax+by=g (g = gcd (A, b)). Using this algorithm we can find three numbers g, X, Y

2. Then we judge C%g==0? If it is not equal to 0, then the equation has no integer solution. If it equals 0, then take the third step.

3. Using g, X, Y, c we find a group of ax+by=c solution x0 = x*c/g, y0 = y*c/g;

4. We now use the basic knowledge 1 to solve the ax+by=c of any set of solutions. We can take advantage of modulo operations when we are seeking the smallest possible x of satisfying conditions:

Example: POJ1061

Test instructions is there are two frogs jumping on the equator, the first frog's starting point is X, each jump m, the second starting from Y each jump n meters, the equator length is L, asked two frogs at least a few steps meet?

We can list the following equations x+km = y+kn mod (l) = + K (m-n) + k1*l = y-x, the code is as follows:

#include <cstdio>#include<cstring>#include<algorithm>#include<iostream>using namespaceStd;typedefLong LongLL;voidGCD (ll A, ll B, LL &d, LL &x, LL &y) {    if(!B) {d=a; x=1; y=0;} Else{gcd (b, a%b, D, y, x); y-= x* (A/b); }}intMain () {LL x, y, M, N, L; CIN>>x>>y>>m>>n>>l; LL a=m-n, B=l, c=y-x;    LL G;    GCD (A, B, G, x, y); if(C%g! =0) {cout<<"Impossible"<<Endl; return 0; } LL x0= c/g*x; //x1 = x0+k*b/gLL BG = b/g>0? b/g:-b/G; X0= (X0%BG+BG)%BG; Here we use the modulo operation to solve the minimum value cout<<x0<<Endl; return 0;}

Solve ax + by = C equations like this

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.