求最大公约数

欧几里得算法或辗转相除法

#include <iostream>

using namespace std;

//循环gcd:greatest common divisor
int gcd(int a,int b)
{
    int tmp;
    while(b){
        tmp = b; b=a%b;a=tmp;
    }
    return a;
}

//递归gcd
int gcd1(int a,int b)
{
    if(b==0) return a;
    gcd1(b,a%b);
}

//最小公倍数least common multiple
int lcm(int a,int b)
{
    return a*b/gcd(a,b);
}


int main()
{
    int a,b;
    while(cin >> a>>b){
        cout << gcd(a,b) << endl;
        cout << lcm(a,b) << endl;
    }
    return 0;
}

你可能感兴趣的:(C++,欧几里得算法,最大公约数,辗转相除法,最小公倍数)