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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。