HDOJ 2669 Romantic (扩展欧几里德)

~~~题目链接~~~


思路:扩展欧几里德,通过扩展欧几里德算法求出X与Y, 它的任意解为(X+K*B', Y-KA') A' = A/gcd(a,b) B' = B/gcd(a,b)


code:

#include <stdio.h>
void gcd(long a, long b, long &d, long &x, long &y)
{
    if(!b) {d = a; x = 1; y = 0;}
    else
    {
        gcd(b, a%b, d, y, x);
        y -= x*(a/b);
    }
}
int main()
{
    long  a = 0, b = 0, d = 0, x = 0, y = 0;
    while(scanf("%ld %ld", &a, &b) != EOF)
    {
        gcd(a, b, d, x, y);
        if(d == 1)
        {
            while(x<0)
            {
                x += b;
                y -= a;
            }
            printf("%ld %ld\n", x, y);
        }
        else
            printf("sorry\n");
    }
    return 0;
}



';

你可能感兴趣的:(HDOJ 2669 Romantic (扩展欧几里德))