最大公約數GCD(Greatest Common Divisor)
最常見的求兩個數的最大公約數的算法是輾轉相除法,也叫歐幾里得算法
該算法的c++語言實現如下:
#include<iostream>
using namespace std;
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int main(){
int a=45,b=10;
cout<<gcd(10,45);
}
Output
5
最小公倍數LCM(Lowest Common Multiple)
最大公倍數=a*b/最大公約數;
它的c++語言實現如下:
#include<iostream>
using namespace std;
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int lcm(int a,int b){
return a*b/gcd(a,b);
}
int main(){
int a=45,b=10;
cout<<gcd(10,45)<<endl;
cout<<lcm(10,45);
return 0;
}
Output
5
90