扩展欧几里得(裸)

来源:互联网 发布:程序员 bug 编辑:程序博客网 时间:2024/06/08 08:27

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2669

•ax + by = (a, b)有解

设一个解为(x, y)

通解为

(x+ k * b / (a, b), y - k * a / (a, b))

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#define maxn  100010typedef long long LL;using namespace std;int extend_gcd(LL a,LL b,LL &x,LL &y);LL gcd(LL a,LL b){    if(a%b==0)return b;    else return gcd(b,a%b);}int main() {    //freopen("in.txt","r",stdin);    LL a,b;    while(cin>>a>>b){        LL x,y;        if(gcd(a,b)!=1){            cout<<"sorry\n";            continue;        }        extend_gcd(a,b,x,y);        if(x<0){            x+=b;            y-=a;        }        cout<<x<<" "<<y<<'\n';    }    return 0;}int extend_gcd(LL a,LL b,LL &x,LL &y){    if(b==0){        x=1;        y=0;        return a;    }    int d=extend_gcd(b,a%b,y,x);    y=y-a/b*x;    return d;}


原创粉丝点击