数学建模:辗转相除法
不妨设两个整数a>b且a除以b商x余c;则a-bx=c,不难看出a,b的最大公约数也是c的约数(因为一个数能除等式左边就一定能除等式的右边),则a,b的最大公约数与b,c的最大公约数相同。
最大公约数的C++代码:
#include <iostream>
using namespace std;
int main()
{
unsigned a,b,c;
while (cin>>a>>b)
{
c = a%b;
while (c)
{
a = b;
b = c;
c = a%b;
}
cout<<b<<endl;
}
return 0;
}
最大公约数的运行结果:
两个数的最小公倍数 = 两个数的乘积/两个数的最大公约数;
下面是最小公倍数的C++代码:
#include <iostream>
using namespace std;
//求a,b的最大公约数
unsigned fun(unsigned a, unsigned b)
{
unsigned c = a%b;
while (c)
{
a = b;
b = c;
c = a%b;
}
return b;
}
int main()
{
unsigned a,b;
while (cin>>a>>b)
{
cout<<a*b/fun(a,b)<<endl;
}
return 0;
}
最小公倍数运行结果: