You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python 3中判断一个给定数字是否为阶乘

判断给定数字是否为阶乘的Python 3实现

Hey there! Let's work through how to build a Python 3 function that checks if a given number is a factorial. Here's a straightforward, easy-to-follow solution that meets your requirements:

def isFactorial(n):
    # 阶乘仅针对非负整数定义,先排除小于1的情况
    if n < 1:
        return "is not a factorial."
    
    factorial_result = 1
    current_num = 1
    
    # 逐步计算阶乘,直到结果大于等于输入数字
    while factorial_result < n:
        current_num += 1
        factorial_result *= current_num
    
    # 对比最终阶乘结果和输入数字,返回对应描述
    return "is a factorial." if factorial_result == n else "is not a factorial."

# 按照要求执行测试输出
print("The number " + str(24) + " " + str(isFactorial(24)))

代码逻辑拆解:

  • 边界情况处理: 首先判断输入数字是否小于1,因为阶乘仅对非负整数有定义(0!和1!的结果都是1),小于1的数不可能是阶乘。
  • 迭代计算阶乘: 从1!开始,逐步用下一个整数乘到当前阶乘结果上,直到结果大于或等于输入数字。
  • 最终校验: 循环结束后,对比计算出的阶乘结果和输入数字,匹配则说明是阶乘,反之则不是。

额外测试示例:

You can test other values to confirm the function works as expected:

  • isFactorial(1) → 返回 "is a factorial."(0!和1!的结果都是1)
  • isFactorial(120) → 返回 "is a factorial."(5! = 120)
  • isFactorial(7) → 返回 "is not a factorial."

内容的提问来源于stack exchange,提问作者Carissa Romero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:03:36