Python 中的 Collatz 序列
pythonserver side programmingprogramming更新于 2025/12/25 14:04:17
假设我们有一个正整数 n,我们必须找到其 Collatz 序列的长度。我们知道 Collatz 序列是按顺序生成的,当 n 为偶数时,n = n/2,否则 n = 3n + 1。当 n = 1 时,此序列结束。
因此,如果输入为 n = 13,则输出将为 10,因为 [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] 这些是序列。
要解决这个问题,我们将遵循以下步骤 −
- 如果 num 与 0 相同,则
- 返回 0
- length := 1
- 当 num 与 1 不同时,执行
- 当 num mod 2 为否则为 0 (3 * num + 1)
- length := length + 1
- 返回长度
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, num): if num == 0: return 0 length = 1 while num != 1: num = (num / 2) if num % 2 == 0 else (3 * num + 1) length += 1 return length ob = Solution() print(ob.solve(13))
输入
13
输出
10
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

