最大公约数
取函数名为gcd(a,b),假定a>b
方法一:暴力求解法
伪代码:
gcd(a,b)
for 1←b to i
if (a mod i==0) and (b mod i==0)
return i
C++代码:
#include <iostream>
using namespace std;
int min(int a,int b){
return a>b?b:a;
}
int gcd(int a,int b){
for(int i=min(a,b);i>=1;i--){
if(a%i==0&&b%i==0){
return i;
}
}
}
int main(){
int a,b;
cin>>a>>b;
cout<<gcd(a,b);
return 0;
}
此方法采取蛮力思想,从a、b之中较小数开始递减,一旦出现同为两数的因数的数,gcd函数即返回该因数。假定a>b,则最坏时间复杂度为O(b)。
该方法还可以进行简单的优化,如下:
gcd(a,b)
for 1←b/2 to i
if (a mod i==0) and (b mod i==0)
return i
将循环起始值设为b/2,可减少循环次数,在数据较大时可略微节省时间。
方法二:辗转