基于辗转相除法的最大公约数和最小公倍数的算法实现
#include<iostream>
#include <string>
using namespace std;
int gcd(int a, int b)
{
if(a < b)
swap(a, b);
while(b)
{
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
// 两数之积 = 两数的最大公约数 * 两数的最小公倍数
int lcm(int a, int b)
{
return a * b / gcd(a, b);
}
int main()
{
int a, b;
while(cin >> a >> b)
{
cout << "the gcd value of " << a
<< " and " << b << " is " << gcd(a, b) << endl;
cout << "the lcm value of " << a
<< " and " << b << " is " << lcm(a, b) << endl;
}
return 0;
}
测试结果: