(1)欧几里得算法
#include <iostream>
#include <stack>
using namespace std;
int GreatestCommonDivisor(int a, int b)
{
int bigger = a > b ? a : b;
int smaller = a < b ? a : b;
if (!(bigger % smaller))
{
return smaller;
}
else
{
return GreatestCommonDivisor(smaller, bigger % smaller);
}
}
int main()
{
cout << " 99 和 54 的最大公约是 : " << GreatestCommonDivisor(99, 54) << endl;
}
(2)更相减损术
int GreatestCommonDivisor(int a, int b)
{
if (a == b)
{
return a;
}
else
{
if (!(a % 2) && !(b % 2))
{
return GreatestCommonDivisor(a>>1, b>>1)<<1;
}
else if ((a % 2) && !(b % 2))
{
return GreatestCommonDivisor(a, b>>1);
}
else if (!(a % 2) && (b % 2))
{
return GreatestCommonDivisor(a>>1, b);
}
else
{
int bigger = a > b ? a : b;
int smaller = a < b ? a : b;
return GreatestCommonDivisor(smaller, bigger - smaller);
}
}
}