Monday, September 21, 2009

最小公倍數(LCM)

最小公倍數(Least Common Multiple, LCM)是兩個整數共有倍數中最小的一個。

計算最小公倍數時,通常會藉助最大公因數(gcd/hcf)來輔助計算。
公式如下:


計算最小公倍數
請輸入兩個數字:
1st: 55
2nd: 44
最大公因數為:11
最小公倍數為:220
請按任意鍵繼續 . . .

#include <iostream>
using namespace std;
int GCD(int a, int b){
if(a%b){
return GCD(b, a%b);
}
else{
return (b);
}
}
int main(){
int x, y, gcd, lcm;
cout << "計算最小公倍數\n" << "請輸入兩個數字:\n";
cout << "1st: ";
cin >> x;
cout << "2nd: ";
cin >> y;
gcd=GCD(x,y);
cout << "最大公因數為:" << gcd << endl;
lcm=x*y/gcd;
cout << "最小公倍數為:" << lcm << endl;
system("Pause");
return 0;
}

No comments:

Post a Comment