zoukankan      html  css  js  c++  java
  • hdu 2669 Romantic

    Problem Description
    The Sky is Sprite.
    The Birds is Fly in the Sky.
    The Wind is Wonderful.
    Blew Throw the Trees
    Trees are Shaking, Leaves are Falling.
    Lovers Walk passing, and so are You. 
    ................................Write in English class by yifenfei

     

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

     此题是最基本的扩展欧几里得算法的应用,也是最好的理解和练手题。代码如下:

    #include<stdio.h>
    int exgcd(int a,int b,__int64&x,__int64 &y)
    {
        if(b==0)
        { x=1;y=0;return a;}
        int r=exgcd(b,a%b,x,y);
        int t=x;x=y;y=t-a/b*y;
        return r;
    }
    int main()
    {
        int a,b;__int64 x,y;//x,y在计算的过程中可能会溢出,故用__int64
        while(scanf("%d%d",&a,&b)!=EOF)
        {
            int m=exgcd(a,b,x,y);
            if(m!=1)
                printf("sorry
    ");
            else {
                x=(x%b+b)%b;
                y=(1-x*a)/b;
                printf("%I64d %I64d
    ",x,y);
            }
        }
        return 0;
    }

    如果不是很理解,可以先理解一下扩展欧几里得算法的原理。

  • 相关阅读:
    2016/1/18
    正则知识点总结
    爬虫反反爬虫:转
    健身与饮食随想--年轻的每一天,都是弥足珍贵的!!!
    python time模块
    c语言求两个数的最大公因数(穷举法,欧几里得算法,递归)
    c语言递归解决汉诺塔问题
    python用函数打印素数(代码未优化)
    羊车门问题提交
    Delphi Tokyo 10.2.3
  • 原文地址:https://www.cnblogs.com/duan-to-success/p/3483871.html
Copyright © 2011-2022 走看看