Python 基础知识简单

最大公约数

“最大公约数”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 gcd(a, b),它接受两个非负整数 ab(不都是零)并使用欧几里得算法返回它们的最大公约数 (GCD)。 GCD 是除 ab 的最大数。

欧几里得算法的工作原理是重复用较大数除以较小数的余数替换较大数,直到余数为 0。最后一个非零余数是 GCD。

约束条件
  • 0 <= a, b <= 10^6
  • a and b are not both zero

示例

Example 1
Input
gcd(48, 18)
Output
6
Explanation

48 % 18 = 12, then 18 % 12 = 6, then 12 % 6 = 0. So GCD is 6.

Example 2
Input
gcd(56, 98)
Output
14
Explanation

98 % 56 = 42, 56 % 42 = 14, 42 % 14 = 0. So GCD is 14.

Example 3
Input
gcd(0, 5)
Output
5
Explanation

GCD(0, n) = n for any positive n.

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

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