求最大公约数是程序中经常需要使用的,大部分人都知道可以使用辗转相除法来求得,但是因为需要使用取模运算,开销较大,那么有没有更好的方法呢?答案是肯定的。一下是代码:
#include<iostream>
using namespace std;
/*1、int GreatestCommonDivisor(int x, int y){
return (!y) ? x : GreatestCommonDivisor(y, x%y);
}*/
/*2、int GreatestCommonDivisor(int x, int y){
if (x < y)
return GreatestCommonDivisor(y, x);
if (y == 0)
return x;
else
return GreatestCommonDivisor(y, x - y);
}*/
bool isEven(int x){
return x & 0x1 ? false : true;
}
int GreatestCommonDivisor(int x, int y){ //3、
if (x < y)
return GreatestCommonDivisor(y, x);
if (y == 0)
return x;
else{
if (isEven(x)){
if (isEven(y)){
return(GreatestCommonDivisor(x >> 1, y >> 1) << 1);
}
else
return GreatestCommonDivisor(x >> 1, y);
}
else{
if (isEven(y))
return GreatestCommonDivisor(x, y >> 1);
else
return GreatestCommonDivisor(y, x - y);
}
}
}
int main(){
int a, b;
cin >> a >> b;
cin.get();
cout << "最大公约数为:" << GreatestCommonDivisor(a, b) << endl;
cin.get();
return 0;
}
上文列出了三种方法,第三种的效率是最高的。(本文大部分代码来自《编程之美》我做了一些修改并实现了isEven()函数)