• 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;
    }
     
  • 相关阅读:
    jquery.tmpl.js 模板引擎用法
    var 的使用
    BUG集锦
    jquery Ajax异步请求之session
    找到多个与名为“Login”的控制器匹配的类型
    蒙板 模态对话框
    mvc通过ActionFilterAttribute做登录检查
    MVC 分页
    MVC 创建线程内的db单例
    Servlet生命周期中的service方法分析
  • 原文地址:https://www.cnblogs.com/a249189046/p/8409232.html
Copyright © 2020-2023  润新知