天天看點

算法筆記5.1 最大公約數與最小公倍數

輸入正整數m,n,求m,n的最大公約數和最小公倍數(最簡潔寫法)

#include<iostream>     
using namespace std;

//輾轉相除法求最大公約數
int gcd(int a,int b){
  if(b==0) return a;
  else return gcd(b,a%b);
}

//最小公倍數
int lcm(int a,int b){
  return a/gcd(a,b)*b;//防止溢出先除最大公約數
}

int main(){
  int m,n;
  while(cin>>m>>n){
    cout<<"最大公約數"<<gcd(m,n)<<endl;
    cout<<"最小公倍數"<<lcm(m,n)<<endl;
  }
  return 0;
}      
算法筆記5.1 最大公約數與最小公倍數