扩展的欧几里德算法-HDU2669

The Sky is Sprite. 
The Birds is Fly in the Sky. 
The Wind is Wonderful. 
Blew Throw the Trees 
Trees are Shaking, Leaves are Falling. 
Lovers Walk passing, and so are You. 
................................Write in English class by yifenfei 

 

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. 

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


#include <iostream> using namespace std; int gcd(int a, int b, int &x, int &y) { if (b == 0) { x = 1, y = 0; return a; } int q = gcd(b, a%b, y, x); y -= a / b * x; return q; } int main(){ int a, b; while (scanf("%d%d", &a, &b) != EOF) { int x, y; if (gcd(a, b, x, y) != 1) cout << "sorry" << endl; else { if (x < 0) { x += b;y -= a; } cout << x << " " << y << endl; } } return 0; }
看测试案例,大概能想到很最大公约数有关,百度百科中:

这里的X

2

,Y

2

是递归返回阶段,上一层的y和x,所以代码中的是y-=a/b*x

 

题目要求X必需为非负数,最后这个是很容易忽略掉的,很好看懂,但是写题目的时候没有想到可以这样写。

 

猜你喜欢

转载自www.cnblogs.com/czc1999/p/10100118.html