您的位置:首页 > 其它

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

2015-09-01 21:19 316 查看
【题目链接】: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: