輾轉相除法求最大公約數,最小公倍數
阿新 • • 發佈:2018-11-25
最大公約數(遞迴):
int gcd(int a,int b){
if(a%b)
return gcd(b,a%b);
return b;
}
最小公約數(迴圈):
int gcd(int a,int b){
int temp;
while(b>0){
temp=a%b;
a=b;
b=temp;
}
return a;
}
最小公倍數:
int lcm(int a,int b){
if(a*b)
return (a*b)/gcd(a,b);
else
return 0;
}
最小公倍數(列舉):
int lcm(int a,int b){
if(a * b == 0)
return 0;//其中一個數為0,則最小公倍數為0;
int temp= a > b ? a : b;//取出較大的一個
while(1)
{
if((temp%a==0) && (temp%b==0))//同時滿足整除a和b的數即是所求
break;
temp++;
}
return temp;
}