Extend Euclid to find general solution and smallest positive integer solution

The solution x and y obtained by expanding Europe are the solution of the equation: ax+by=gcd(a,b)

x0=x*c/gcd

y0=y*c/gcd

x0, y0 is the solution of the equation ax+by=c

So how to find the general solution of the equation ax+by=c?

Let x0 shift to the left and right by n divisions, the change of y (n is an integer)

y0=(c-a*x0)/b

y1=(c-ax1)/b=(c-a(x0+n))/b=y0-a/b*n

That is to say x1=x0+n; y1=y0-a/b*n

Convert a/b to an integer:

x1=x0+b*n

y1=y0-a*n

Does this get a general solution? Think about it again, can we really get a general solution every time x changes by b units?

b/=gcd(a,b)

a/=gcd(a,b)

This is fine, because we minimize a and b so that the coefficient before n is the smallest, and more solutions can be obtained

int x,y,kx,ky;
int gcd=extgcd(a,b,x,y);
x*=c/gcd;
y*=c/gcd;
kx=b/gcd;
ky=-a/gcd;
//通解就是:x+kx*n,y+ky*n

After getting the general solution, how to find the smallest positive integer solution?

Known: x+b/gcd*n is the general solution of x (equivalent to x can increase or decrease each time: an integer multiple of b/gcd)

The smallest positive integer solution is x=(x+b/gcd*n)%(b/gcd)=x%(b/gcd)

If x<=0, then x+=b/gcd

int x,y;
int g=extgcd(a,b,x,y);
x*=c/g;
b/=g;
if(b<0)b=-b;
int ans=x%b;
if(ans<0)ans+=b;

Guess you like

Origin blog.csdn.net/weixin_43244265/article/details/104428549