Python 中的逆阶乘
pythonserver side programmingprogramming更新于 2025/12/26 16:12:17
假设我们有一个数字 a,我们必须找到 n,使得 n(n!)的阶乘与 a 相同。众所周知,阶乘 n = n * (n - 1) * (n - 2) * ... * 1。如果没有这样的整数 n,则返回 -1。
因此,如果输入为 a = 120,则输出将为 5。
为了解决这个问题,我们将遵循以下步骤 −
- i := 0, num := 1
- L:= a new list
- while i < a,执行
- i := num 的阶乘
- 将 i 插入 L 的末尾
- num := num + 1
- 如果 a 在 L 中,则
- 返回 (a 在 L 中的索引) +1
- 否则,
- 返回 -1
让我们看看下面的实现以便更好地理解 −
示例
import math class Solution: def solve(self, a): i,num=0,1 L=[] while i < a : i=math.factorial(num) L.append(i) num+=1 if a in L : return L.index(a)+1 else : return -1 ob = Solution() print(ob.solve(120))
输入
120
输出
5
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

