Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.
InputThe input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)
Outputoutput nonnegative integer X and integer Y, if there are more answers than the X smaller one will be choosed. If no answer put "sorry" instead.
Sample Input
77 51 10 44 34 79
Sample Output
2 -3 sorry 7 -3
扩展欧几里德的模板题,只有当1模上gcd等于0的时候,解才存在。
解存在的时候,通过扩展欧几里德求出 特解x0,y0;
然后用通解公式x=x0+k*(b/gcd)
y=y0-k*(a/gcd)
求出最小非负数x,和对应的y;
代码如下:
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; LL a,b; LL exgcd(LL a,LL b,LL &x, LL &y) { if(b==0) { x=1; y=0; return a; } LL r=exgcd(b,a%b,x,y); LL t=x; x=y; y=t-a/b*y; return r; } int main() { LL x,y,x1,y1,k; while(cin>>a>>b) { LL gcd=exgcd(a,b,x,y); LL c=1; if(c%gcd!=0) puts("sorry"); else { x1=((x*c/gcd)%(b/gcd)+(b/gcd))%(b/gcd); k=(x1-x)/(b/gcd); y1=y-(a/gcd)*k; cout<<x1<<" "<<y1<<endl; } } return 0; }