Python 基礎知識中等

使用遞歸的 LCM

「使用遞歸的 LCM」問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 lcm(a, b),使用遞迴計算兩個正整數 ab 的最小公倍數 (LCM)。使用關係式:LCM(a, b) = (a * b) // HCF(a, b)。也使用遞歸實作 HCF 助手。

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

範例

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

HCF(4,6) = 2. LCM = (4*6) // 2 = 12. The multiples of 4 are 4,8,12,... and multiples of 6 are 6,12,... The smallest common is 12.

Example 2
Input
a = 12, b = 15
Output
60
Explanation

HCF(12,15) = 3. LCM = (12*15) // 3 = 60.

Example 3
Input
a = 7, b = 3
Output
21
Explanation

HCF(7,3) = 1. LCM = (7*3) // 1 = 21.

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

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