Number Theory: Extended Euclidean Algorithm

_______________________ I do not know where to go, but I've been on the road.

(Trade-integer!)

 

 

Summary:

 

codes:

#include<iostream>
#include<algorithm>
using namespace std;
int a,b,d,x,y;
int exgcd(int a,int b,int& x,int& y)
{
	if(b==0) 
	{
		x=1;
		y=0;
		return a;
	}
	int t=exgcd(b,a%b,x,y);
	int x0=x;
	int y0=y;
	x=y0;
	y=x0-(a/b)*y0;
	return t; 
}

int main()
{
	while(cin>>a>>b>>d && a && b && d)
	{
		int t=__gcd(a,b);
		a/=t;b/=t;d/=t;
		exgcd(a,b,x,y);
		x=d*x;
		y=d*y;
		
		int tx=(x%b+b)%b;//为神木模b? 
		int ty=(d-a*tx)/b;
		if(ty<0) ty=-ty;
		
		y=(y%a+a)%a;
		x=(d-b*y)/a;
		if(x<0) x=-x;
		
		if(x+y>tx+ty) 
		{
			x=tx;
			y=ty;
		}
		cout<<x<<' '<<y<<endl;
	}
	return 0;
} 

  Reference: https://blog.csdn.net/u013008291/article/details/38359073

 

Guess you like

Origin www.cnblogs.com/dragondragon/p/11294839.html