这里提供了一种高效的解决方法,值得借鉴。 需要注意的是程序GCD函数的第二行,当其中一个值为0的时候返回另外一个值,否则导致栈溢出(因为没有非递归的结束条件!) 代码如下: //编程之美2.7 最大公约数 #include <iostream> using namespace std; template<class T> T Gcd(T x, T y) { if(x<y) return Gcd(y,x); if(!y) return x; if(x&static_cast<T>(1) == 0)//x is even { if (y & static_cast<T>(1) == 0) { return 2*Gcd(x>>2,y>>2); } else { return Gcd(x>>2,y); } } else { if (y & static_cast<T>(1) == 0) { return Gcd(x,y>>2); } else return Gcd(x-y,y); } } int main() { while (1) { int a = abs(rand()); int b = abs(rand()); cout<<a<<" "<<b<<" :"<<Gcd(a,b)<<endl; } return 0; }