HDU2669 Romantic (扩展欧几里德)

Posted a249189046

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU2669 Romantic (扩展欧几里德)相关的知识,希望对你有一定的参考价值。

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. 

InputThe input contains multiple test cases. 
Each case two nonnegative integer a,b (0<a, b<=2^31) 
Outputoutput 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

扩展欧几里德的模板题,只有当1模上gcd等于0的时候,解才存在。
解存在的时候,通过扩展欧几里德求出 特解x0,y0;
然后用通解公式x=x0+k*(b/gcd)
y=y0-k*(a/gcd)
求出最小非负数x,和对应的y;

代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL a,b;
LL exgcd(LL a,LL b,LL &x, LL &y)
{
  if(b==0)
  {
      x=1;
      y=0;
      return a;
  }
    LL r=exgcd(b,a%b,x,y);
    LL t=x;
    x=y;
    y=t-a/b*y;
    return r;
}
int main()
{
    LL x,y,x1,y1,k;
    while(cin>>a>>b)
    {
      LL gcd=exgcd(a,b,x,y);
      LL c=1;
      if(c%gcd!=0)
      puts("sorry");
      else
      {
        x1=((x*c/gcd)%(b/gcd)+(b/gcd))%(b/gcd);
        k=(x1-x)/(b/gcd);
        y1=y-(a/gcd)*k;
        cout<<x1<<" "<<y1<<endl;
      }
    }
    return 0;
}

 

 

以上是关于HDU2669 Romantic (扩展欧几里德)的主要内容,如果未能解决你的问题,请参考以下文章

HDU2669 Romantic (扩展欧几里德)

hdu_2669 Romantic(扩展欧几里得)

hdu 2669 Romantic 扩展欧几里得

HDU 2669 Romantic 扩展欧几里得

hdu 2669 Romantic扩展欧几里得(模板题)

hdu-2669 Romantic---扩展欧几里得