HDU 2669 romantic

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.