求最大公約數

歐幾里得算法或輾轉相除法

#include <iostream>

using namespace std;

//循環gcd:greatest common divisor
int gcd(int a,int b)
{
    int tmp;
    while(b){
        tmp = b; b=a%b;a=tmp;
    }
    return a;
}

//遞歸gcd
int gcd1(int a,int b)
{
    if(b==0) return a;
    gcd1(b,a%b);
}

//最小公倍數least common multiple
int lcm(int a,int b)
{
    return a*b/gcd(a,b);
}


int main()
{
    int a,b;
    while(cin >> a>>b){
        cout << gcd(a,b) << endl;
        cout << lcm(a,b) << endl;
    }
    return 0;
}
發佈了71 篇原創文章 · 獲贊 30 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章