代码改变世界

Romantic(扩展欧几里得)

2019-08-14 14:44  木木王韦  阅读(165)  评论(0)    收藏  举报

Romantic

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 Xa + Yb = 1. If no such answer print “sorry” instead.
Input
The input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)
Output
output 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

这道题套用一个exgcd函数,然后注意x是非负数,所以当x是负数时进行的操作是ax+by=a*(x+b)+b*(y-a),使x变为非负数

ac代码:

#include<iostream>
#include<algorithm>

using namespace std;
int flag;
long long int exgcd(long long int a,long long int b,long long int &x,long long int &y){
	if(b==0){
		x=1;
		y=0;
		
		return a;
	}
	int r=exgcd(b,a%b,x,y);
	int t=x;
	x=y;
	y=t-(a/b)*y;
	return r;
}
int main(){
	long long int n,m,y,x;
	while(cin>>n>>m){
		flag=0;
		
		if(exgcd(n,m,x,y)==1) flag=1;
		if(x<0){
			x+=m;
			y-=n;
		}
		if(flag){
			cout<<x<<" "<<y<<endl;
		}
		else cout<<"sorry"<<endl;
	}
	return 0;
}