HDU2669 Romantic (擴展歐幾裏德)
阿新 • • 發佈:2018-02-03
def eve test sample include choose each inpu tell 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; }
HDU2669 Romantic (擴展歐幾裏德)