Uvalive 6428 A+B(扩展欧几里得算法)

来源:互联网 发布:海南知和行书局 编辑:程序博客网 时间:2024/06/04 18:11

【题目链接】:click here~~

【题目大意】:求满足类似a*x+b*y=c的方程,问是否存在整数解(a,b,c<10^18)

【思路】扩展欧几里得算法,注意特判等于零的情况

代码:

#include <bits/stdc++.h>using namespace std;typedef long long LL;LL a,b,c;LL gcd(LL a,LL b){    return b==0?a:gcd(b,a%b);}// 求解 a * n + b * m = gcd(n, m)// 求得一组解 (x0, y0)// 解系: (x0 + k * b / g, y0 - k * a / g)LL ext_gcd(LL &a,LL &b,LL n,LL m) // Extended Euclidean Algorithm{    if(m==0)    {        a=1;        b=0;        return n;    }    LL d=ext_gcd(b,a,m,n%m);    b-=n/m*a;    return d;}int main(){    while(scanf("%lld %lld %lld",&a,&b,&c)!=EOF)    {        if(!a&&!b)  // special judge the a and b if it value 0        {            if(!c) puts("YES");            else puts("NO");            continue;        }        if(!a)        {            if((c%b)==0) puts("YES");            else puts("NO");            continue;        }        if(!b)        {            if((c%a)==0) puts("YES");            else puts("NO");            continue;        }        LL x,y,g;        g=ext_gcd(x,y,a,b);        if((c%g)!=0)        {            puts("NO");            continue;        }        LL x0=b/g;        LL y0=a/g;        x=((c/g%x0)*(x%x0)%x0+x0)%x0;        y=(c-x*a)/b;        bool ok=false;        while(y>0)        {            if(gcd(x,y)==1)            {                ok=true;                break;            }            x+=x0;y-=y0;        }        if(ok) puts("YES");        else puts("NO");    }    return 0;}


0 0