b249中等

107 彰雲嘉區資訊學科能力競賽(2018)|最大公因數與最小公倍數

以0作結束符,不能把0納入LCM。初始化g=0、l=1。

解題思路

以0作結束符,不能把0納入LCM。初始化g=0、l=1。

讀到正整數x時,g更新為gcd(g,x),l更新為l/gcd(l,x)×x;前者保留共同最小質因數指數,後者保留最大指數。

全部讀完後,結合律保證兩值分別是全體GCD、LCM。使用任意精度支援巨大最小公倍數。

n筆數需 O(n)次Euclid與大整數乘除,實際時間依各數及LCM位數;串流額外空間依最大中間大整數位數。

Step-by-step animation

教學小例:任意精度GCD與LCM逐項更新

回報動畫錯誤
步驟 1 / 3

輸入6,10,15

先得g=6、l=6

先得g=6、l=6
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
cpp_int gcdBig(cpp_int a, cpp_int b) {
    if (a < 0)
        a = -a;
    if (b < 0)
        b = -b;
    while (b != 0) {
        cpp_int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main() {
    cpp_int x, g = 0, l = 1;
    while (cin >> x && x != 0) {
        g = gcdBig(g, x);
        l = l / gcdBig(l, x) * x;
    }
    cout << g << ' ' << l << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多