对于a’ = b, b’ = a % b 而言,我们求得 x, y使得 a’x + b’y = Gcd(a’, b’)
由于b’ = a % b = a - a / b * b (注:这里的/是程序设计语言中的除法,即整数除法,结果舍去小数部分)
那么可以得到:
a’x + b’y = Gcd(a’, b’) ===>
bx + (a - a / b * b)y = Gcd(a’, b’) = Gcd(a, b) ===>
ay +b(x - a / b*y) = Gcd(a, b)
因此对于a和b而言,他们的相对应的p,q分别是 y和(x-a/b*y)
使用扩展欧几里德算法解决不定方程的办法
对于不定整数方程pa+qb=c,若 c mod Gcd(a, b)=0,则该方程存在整数解,否则不存在整数解。
题目:
Romantic
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2590 Accepted Submission(s): 1023
Problem Description
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.
Input
The input contains multiple test cases.
Each case two nonnegative integer a,b (0
#include <iostream>
using namespace std;
typedef long long LL;
LL exgcd(LL m, LL n, LL & x, LL & y)
{
if (n == 0)
{
x = 1, y = 0;
return m;
}
LL r = exgcd(n, m%n, y, x);
y -= m / n * x;
return r;
}
int main()
{
LL m, n, r1, r2;
while (cin >> m >> n)
{
if (exgcd(m, n, r1, r2) != 1)
puts("sorry");
else
{
while (r1 < 0)
{
r1 += n;
r2 -= m;
}
printf("%I64d %I64d\n", r1, r2);
}
}
return 0;
}