码迷,mamicode.com
首页 > 编程语言 > 详细

扩展的欧几里德算法-HDU2669

时间:2018-12-11 01:34:27      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:while   and   content   multi   技术分享   nbsp   main   more   div   

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必需为非负数,最后这个是很容易忽略掉的,很好看懂,但是写题目的时候没有想到可以这样写。

 技术分享图片

扩展的欧几里德算法-HDU2669

标签:while   and   content   multi   技术分享   nbsp   main   more   div   

原文地址:https://www.cnblogs.com/czc1999/p/10100118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!