hdu-2669 Romantic---扩展欧几里得
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2669
题目大意:
给定a b,求ax+by = 1是否有解,输出x为正数的最小的解
解题思路:
a b互质才有解,下面的方法可求出最小正数的x的解
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 ll extgcd(ll a, ll b, ll&x, ll&y)//ax+by = gcd(a, b)的解。返回值为gcd 5 { 6 ll d = a; 7 if(b) 8 { 9 d = extgcd(b, a % b, y, x); 10 y -= (a / b) * x; 11 } 12 else x = 1, y = 0; 13 return d; 14 } 15 int main() 16 { 17 ll a, b; 18 while(cin >> a >> b) 19 { 20 if(__gcd(a, b) != 1) 21 { 22 cout<<"sorry"<<endl; 23 continue; 24 } 25 ll x, y; 26 extgcd(a, b, x, y); 27 x = ((x % b) + b) % b; 28 y = (1 - a * x) / b; 29 cout<<x<<" "<<y<<endl; 30 } 31 return 0; 32 }
越努力,越幸运