Use an Extended Euclidean algorithm.
For the first two integers $ X_1 and Y_1 $, we can calculate $ ax_1 + by_1 = gcd (a, B) $. Let's take the next step and get the formula:
\ Begin {equation} ax_1 + by_1 = gcd (a, B) = gcd (B, A \ % B) = bx_2 + (A \ % B) Y_2 \ end {equation}
In this way, $ X_1 = Y_2 $ and $ Y_1 = X_2-(A/B) Y_2 $ are obtained. In this way, we can use recursion to calculate the Extended Euclidean.
Note that the solutions that meet the conditions are not unique. For any integer $ K $, we have $ x = x + kb $, $ Y = Y-ka $, the answer is the smallest positive integer $ x $ in the numerous solutions and the paired $ y $.
The Code is as follows:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <iostream> 4 #include <cstring> 5 using namespace std; 6 typedef long long LL; 7 void exgcd(LL a, LL b, LL &d, LL &x, LL &y) 8 { 9 if( b == 0 )10 {11 d = a;12 x = 1;13 y = 0;14 }15 else16 {17 exgcd(b, a%b, d, x, y);18 int t = x;19 x = y;20 y = t - (a/b)*x;21 }22 }23 int main(int argc, char *argv[])24 {25 LL x, y, d, a, b;26 while(cin>>a>>b)27 {28 exgcd(a, b, d, x, y);29 if( d == 1 )30 {31 while( x < 0 )32 {33 x += b;34 y -= a;35 }36 cout<<x<<" "<<y<<endl;37 }38 else39 {40 printf ( "sorry\n" );41 }42 }43 }
HDU 2669 romantic