Python 基礎知識簡單

最大公約數

“最大公約數”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 gcd(a, b),它接受兩個非負整數 ab(不都是零)並使用歐幾里德演算法傳回它們的最大公約數 (GCD)。 GCD 是除 ab 的最大數。

歐幾裡得演算法的工作原理是重複用較大數除以較小數的餘數替換較大數,直到餘數為 0。最後一個非零餘數是 GCD。

約束條件
  • 0 <= a, b <= 10^6
  • a and b are not both zero

範例

Example 1
Input
gcd(48, 18)
Output
6
Explanation

48 % 18 = 12, then 18 % 12 = 6, then 12 % 6 = 0. So GCD is 6.

Example 2
Input
gcd(56, 98)
Output
14
Explanation

98 % 56 = 42, 56 % 42 = 14, 42 % 14 = 0. So GCD is 14.

Example 3
Input
gcd(0, 5)
Output
5
Explanation

GCD(0, n) = n for any positive n.

Need a Hint?
考慮使用特定於數字的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。