Romatic HDU2699

来源:互联网 发布:金蝶软件补丁 编辑:程序博客网 时间:2024/05/17 00:15

题意:给两个非负整数 a 和 b,要找到一个非负整数 x 和一个整数 y,使得满足 x×a+y×b=1

思路:用扩展欧几里得,因为要求 x 非负,所以可以把式子写成 x×a+y×b+a×ba×b=a×(b+x)+b×(ya)=1。欧几里得算出 x 和 y 后还要判断下 x,如果 x 小于 0,则用上面的推导式分别给 x 和 y 加上 b 和 -a 就好。

代码:

#include<cstdio>#include<cstring>#include<cstdlib>#include<stack>#include<queue>#include<utility>#include<vector>#include<cmath>#include<set>#include<map>#include<iostream>#include<algorithm>using namespace std;typedef long long LL;LL ExtendGcd(LL a, LL b, LL& x, LL& y){    LL r;    if(b == 0){        x = 1;        y = 0;        return a;    }    else{        r = ExtendGcd(b, a%b, y, x);        y -= (a/b)*x;    }    return r;}int main(){    LL a, b;    while(scanf("%lld%lld", &a, &b) == 2){        LL x, y;        if(ExtendGcd(a, b, x, y) == 1){            while(x < 0){                x += b;                y -= a;            }            printf("%lld %lld\n", x, y);        }        else{            printf("sorry\n");        }    }    return 0;}
原创粉丝点击