Python 基礎知識簡單

兩個分數相加

「兩個分數相加」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 add_fractions(a, b, c, d) ,它採用四個整數來表示兩個分數 a/b 和 c/d,並以最簡單的形式(透過 GCD 約簡)以元組(分子、分母)形式傳回結果。

分數相加的公式為:a/b + c/d = (a*d + b*c) / (b*d),然後將分子和分母除以它們的 GCD 來簡化。

約束條件
  • 1 <= b, d <= 1000
  • -1000 <= a, c <= 1000
  • b and d are not zero

範例

Example 1
Input
add_fractions(1, 2, 1, 3)
Output
(5, 6)
Explanation

1/2 + 1/3 = (1×3 + 2×1) / (2×3) = 5/6. GCD(5,6) = 1, so result is 5/6.

Example 2
Input
add_fractions(2, 4, 3, 6)
Output
(1, 1)
Explanation

2/4 + 3/6 = (2×6 + 4×3) / (4×6) = 24/24 = 1/1.

Example 3
Input
add_fractions(1, 3, 2, 3)
Output
(1, 1)
Explanation

1/3 + 2/3 = 3/3 = 1/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 資源

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