1. 程式人生 > >gcd 模板 以及最小公倍數

gcd 模板 以及最小公倍數

下面程式碼是求最大公約數
//遞迴版
int gcd(int a,int b){
    return b?gcd(b,a%b):a;
}

//非遞迴版
int gcd(int a,int b)
{
    while(b)
    {
        int t=a%b;
        a=b;
        b=t;
    }
    return a;
}


最小公倍數等於:原來兩個數a,b的乘積除以最大公約數





交換兩個數的值:
if(a<b)
            a=a^b,b=a^b,a=a^b;

gcd
#include<stdio.h>

int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}

int main()
{
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        if(a<b)
            a=a^b,b=a^b,a=a^b;
        printf("%d\n",gcd(a,b));
    }
    return 0;
}


最大公約數
#include<stdio.h>

#define LL long long
LL gcd(LL a,LL b)
{
    return b?gcd(b,a%b):a;
}

int main()
{
    LL a,b;
    while(scanf("%lld%lld",&a,&b)!=EOF)
    {
        if(a<b)
            a=a^b,b=a^b,a=a^b;
        printf("%lld\n",a*b/gcd(a,b));
    }
    return 0;
}