九度 1056 最大公约数

题目来源:http://ac.jobdu.com/problem.php?pid=1056

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

//如果求,x, y的公约数,如果x = k*x1, y = k*y1,则:Gcd(x, y) = k*Gcd(x1, y1);
//如果x = p*x1, 其中p为素数,并且y%p != 0, 则:Gcd(x, y) = Gcd(p*x1, y1) = Gcd(x1, y);
int Gcd(int a, int b)
{
    if(a < b)
        return Gcd(b, a);
    if(b == 0)
        return a;
    if(!(a & 1))
    {
        if(!(b & 1))
            return (Gcd((a >> 1), (b >> 1)) << 1);
        else
            return Gcd((a >> 1), b);
    }
    else
        if(!(b & 1))
            return Gcd(a, (b >> 1));
        else
            return Gcd(b, a-b);
}

int main()
{
    int a, b;
    while(~scanf("%d %d", &a, &b))
        printf("%d\n", Gcd(a, b));
    return 0;
}

常规

#include <cstdio>
#include <cstring>
#include <iostream>

int Gcd(int a, int b)
{
    if(!b)
        return a;
    return Gcd(b, a%b);
}

int main()
{
    int a, b;
    while(~scanf("%d %d", &a, &b))
        printf("%d\n", Gcd(a, b));
    return 0;
}


你可能感兴趣的:(数论,数学)