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
题意:
给出非负整数a,b,输出X的最小正整数解和对应的Y。其中X为非负整数,Y为整数。如果方程无解,输出sorry。
思路分析:
首先,枚举是别想了。
aX+bY=1,这个方程不就是ax+by=c嘛。线性同余方程模板题。
直接上代码。
#include <iostream>
#define ll long long
using namespace std;
ll exgcd(ll a, ll b, ll &x, ll &y) //扩展欧几里得
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll q = exgcd(b, a%b, x, y);
ll tmp = x;
x = y;
y = tmp - (a/b)*y;
return q;
}
int main()
{
ll x, y, a, b ,c = 1;
while(cin>>a>>b)
{
ll d = exgcd(a,b,x,y);
if(c%d != 0) cout<<"sorry"<<endl;
else
{
ll r = b/d;
ll X = (c/d*x%r + r)%r; //先求出X正整数解,然后求Y
ll Y = (c-a*X)/b;
cout<<X<<" "<<Y<<endl;
}
}
return 0;
}
本文介绍了解决线性同余方程aX+bY=1的方法,通过扩展欧几里得算法寻找非负整数X和整数Y的最小正整数解。提供了完整的代码实现,并解释了如何处理无解情况。

被折叠的 条评论
为什么被折叠?



