a024. 最大公因數(GCD) 5/16/2025

解法一、函式庫

評分結果(參考) : AC (2ms, 348KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b;
    cin >> a >> b;
    cout << __gcd(a, b);

    return 0;
}

解法二、輾轉相除法

🔹 a, b 互取餘數直到餘數 = 0

例如 gcd(49, 28) 的計算步驟

  1. 49 % 28 = 21
  2. 28 % 21 = 7
  3. 21 % 7 = 0
  4. gcd(49, 28) = 7

✅ 完整代碼

評分結果(參考) : AC (2ms, 332KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b;
    cin >> a >> b;

    while(a%b != 0){
        a = a%b;
        swap(a, b);
    }
    cout << b;

    return 0;
}

解法三、暴力解

// 作者在偷懶