Python 基礎知識簡單

最大公因數(HCF)

「最高公因數 (HCF)」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 find_hcf(a, b),它接受兩個正整數 ab 並傳回它們的最高公因數 (HCF)。 HCF 是兩個數相除不留餘數的最大正整數。

例如,12和18的HCF是6,因為6是能整除12和18的最大數。

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

範例

Example 1
Input
find_hcf(12, 18)
Output
6
Explanation

Factors of 12: 1, 2, 3, 4, 6, 12. Factors of 18: 1, 2, 3, 6, 9, 18. Common factors: 1, 2, 3, 6. Highest is 6.

Example 2
Input
find_hcf(24, 36)
Output
12
Explanation

Factors of 24: 1, 2, 3, 4, 6, 8, 12, 24. Factors of 36: 1, 2, 3, 4, 6, 9, 12, 18, 36. Highest common factor is 12.

Example 3
Input
find_hcf(7, 13)
Output
1
Explanation

7 and 13 are both prime numbers with 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 資源

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