//求最大公约数
//利用欧几里得算法(也叫辗转相除法)
#include "stdafx.h"
//递归程序
unsigned int GcdRecursively (unsigned int x, unsigned int y)
{
if (x == 0 || y == 0)
return x+y;//return非0值
return GcdRecursively(y,x%y);
}
//循环程序
unsigned int GcdIteratively (unsigned int x, unsigned int y)
{
if (x == 0 || y == 0)
return 0;
unsigned int temp = x % y;
while (temp)
{
x = y;
y = temp;
temp = x % y;
}
return y;
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int x = 90;
unsigned int y = 60;
unsigned int gcd = GcdRecursively(x,y);
gcd = GcdIteratively(x,y);
return 0;
}
但是循环程序不够简洁,有重复的部分。这样写更好:
unsigned int GcdIteratively2 (unsigned int x, unsigned int y)
{
if (x == 0 || y == 0)
return 0;
unsigned int remain = 0;
while (y)
{
remain = x % y;
x = y;
y = remain;
}
return x;
}