求最大公约数最直接的办法是从两数中较小数与2之间的所有整数中一个一个的找。但这个方法有点浪费。
有两种有名的方法:1.辗转相除法2.更相减损之术这两种方法比较有名,而且现在人教版的高中数学中已经介绍了这两种方法。
下面这个是第2个,因为它只需要加减法就可以,效率高。
int MaxFactor(unsigned int a,unsigned int b)
{
while(a!=b)
{
if(a>b){a=a-b;}
else {b=b-a;}
}
return a;
}
void main()
{
unsigned int x=MaxFactor(16,12);
}
求最小公倍数只要用 a*b/MaxFactor(a,b);