C++中用辗转相除法求两个数的最大公约数和最小公倍数

两个数的最大公约数:不能大于两个数中的最小值,算法口诀:小的给大的,余数给小的,整除返回小的,即最大公约数,(res=max%min)==0?  max=min,min=res return min; 

两个数的最小公倍数:等于两数之和除以两个数的最大公约数 a*b/(LCM(a,b));

#include <iostream>
using namespace std;


/*求最大公约数,辗转相除法来求最小公倍数*/
int getLCM(int a, int b)
{
    int max = (a > b ? a : b);
    int min = (a < b ? a : b);
    int res = max%min;
    while (res)
    {
        max = min;//小的给大的
        min = res;//余数给小的
        res = max%min;
    }
    return min;//整除返回小的
}

/*求最小公倍数*/
int getGCD(int a, int b)
{
    //最小公倍数等于两数之积除以最大公约数
    return a*b / getLCM(a, b);
}

int main(int argc, char *argv[])
{
    
    cout << getGCD(45, 30) << endl;
    cout << getLCM(45, 30) << endl;

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/ttss/p/4100850.html