用 Python 编写程序检查某个数是否可​​以写成不同阶乘数之和

pythonserver side programmingprogramming更新于 2026/1/13 0:44:17

假设我们有一个正数 n,我们必须检查 n 是否可以写成唯一正阶乘数之和。

因此,如果输入为 n = 144,则输出将为 True,即 4! + 5! = 24 + 120 = 144

为了解决这个问题,我们将遵循以下步骤 −

  • fact := 1

  • res := a new list

  • x := 2

  • 当 fact <= n 时,执行

    • 在 res 末尾插入 fact

    • fact := fact * x

    • x := x + 1

  • 对于 res -1 到 0 范围内的 i,减少 1,执行

    • 如果 n >= res[i],然后

      • n := n - res[i]

  • 当 n 与 0 相同时返回 true

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
def solve(self, n):
   fact = 1
   res = []
   x = 2
   while fact <= n:
      res.append(fact)
      fact = fact * x
      x += 1
   for i in range(len(res)-1,-1,-1):
      if n>=res[i]:
         n-=res[i]
   return n==0
ob = Solution()
print(ob.solve(144))

输入

144

输出

True

相关文章


有用资源