Python 基礎知識中等

使用遞歸的 HCF

“HCF using Recursion”問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 hcf(a, b),使用遞歸計算兩個正整數 ab 的最高公因數 (HCF),也稱為最大公約數 (GCD)。使用歐幾里德演算法:HCF(a, b) = HCF(b, a % b),基本情況 HCF(a, 0) = a。

約束條件
  • 1 <= a, b <= 10^6

範例

Example 1
Input
a = 12, b = 8
Output
4
Explanation

12 = 4*3, 8 = 4*2. The largest common factor is 4.

Example 2
Input
a = 54, b = 24
Output
6
Explanation

54 = 6*9, 24 = 6*4. HCF is 6.

Example 3
Input
a = 17, b = 13
Output
1
Explanation

17 and 13 are both prime and share no common factors other than 1.

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 資源

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