十多年后,我想提供一种 Python 方法,灵感来自于你对乘法感兴趣,factorial(n) * n+1
基本情况是0
,1
结果是1
,那么:
def fact_var(num):
a, b, i = 1,2,2 # base cases and our i counter.
while i < num: # if i is equal to num, we're done, last product will be at return.
c = a * b # start to multiply and save in c.
i+=1 # add 1 to i because we want to multiply next number with c (in the next iteration).
a, b = c, i # update variables to the next iteration.
return a * b if num > 1 else 1 # last product occurs here is num is greater than 1.
print(fact_var(100000))
对于 100 000 的阶乘,在我的机器上最多需要 5 秒,我希望它可以为文档和即将到来的观众服务!
附言。同样的想法对计算斐波那契很有用,斐波那契是求和而不是乘法。