Week Five Practice I (extended Euclidean algorithm)

Source: Internet
Author: User

I-Number theory, linear equationsTime limit:1000MS Memory Limit:32768KB 64bit IO Format:%i64d & Amp %i64u

Description

The Sky is Sprite.  the Birds is Fly in the Sky.   the Wind is Wonderful.   blew Throw the Trees  Trees is Shaking, Leaves is falling.   Lovers Walk passing, and so is you.   ......... ............... Write in 中文版 class by Yifenfei 

Girls is clever and bright. In HDU every girl like math. Every girl like to solve math problem! Now, you have 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.  

Input

The input contains multiple test cases.Each case , nonnegative integer A, b (0<a, b<=2^31)

Output

Output nonnegative integer X and integer Y, if there is more answers than the X smaller one would be choosed. If no answer put "sorry" instead. 

Sample Input

77 5110 4434 79

Sample Output

2-3sorry7-3Puzzle : Purple book p313The extended Euclidean algorithm is used to solve a set of X, Y, and X*A+Y*B=GCD (A, b) in a known A/b

X*A+Y*B=GCD (A, B) =gcd (b,a%b) =x*b+y*a%b=x*b+y* (a-a/b*b) =y*a+ (x-a/b*y) because known Euclidean algorithm gcd (A, B) =gcd (B,A%B);

Note: A-a/b*b=a%b the linear combination of a A and a B as a linear combination of a%b. According to my output diagram can be seen: A, b are decreasing, when a reduced to 0 o'clock, we can draw x=1,y=0; And then you can go back and find the final x, Y.

#include <iostream>using namespacestd;voidgcdintAintBint& D,int&x,int&y) {    if(!b) {d=a;x=1; y=0; //cout<<d<< "" <<x<< "" <<y<<endl; //Output    }    Else{gcd (b,a%b,d,y,x); //cout<<b<< "<<a%b<<" "<<d<< " "<<y<<" <<x<<endl;//Outputy-=a/b*x; //cout<<x<< "" <<y<<endl; //Output    }}intMain () {intA,b,d,x,y;  while(cin>>a>>b) {gcd (a,b,d,x,y); if(d!=1) cout<<"Sorry"<<Endl; Else        {              while(x<0)//x cannot be less than 0x+=b,y-=A; cout<<x<<" "<<y<<Endl; }    }    return 0;}

Week Five Practice I (extended Euclidean algorithm)

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.