Python factorial sum method
Title description:
Get the integer input by the user n, output the value of 1! 2! … n!.
If the input value is 0, negative, non-numeric or non-integer, a prompt message will be output: Incorrect input, please enter a positive integer.
(Recommended learning: Python video tutorial)
Method one:
#factTest1 def main(): a = input() sum = 0 if a.isdigit(): n = eval(a) if n > 0: fact = 1 for i in range(1, n+1): fact *= i sum += fact print(sum) else: print("输入有误,请输入正整数") else: print("输入有误,请输入正整数") main()
Method two: Recursive thinking
#factTest2 import sys sys.setrecursionlimit(5000) def getSum(i): sum = 0 if i==0: return 0 else: for x in range(1,i+1): sum += fact(x) return sum def fact(m): if m==0: return 1 else: return m*fact(m-1) def main(): n = input() if n.isdigit(): a = eval(n) if a>0: result = getSum(a) print(result) else: print("输入有误,请输入正整数") else: print("输入有误,请输入正整数") main()
Summary of the problem:
When using the recursive method to find the factorial of 1024, an exception occurred: RecursionError: maximum recursion depth exceeded in comparison, exceeded The maximum depth of recursion. Some netizens mentioned that the default maximum recursion depth in Python is 1000, but in actual testing, my computer experienced an exception when it reached 997. I don’t know what determines this. Therefore, in order to be able to calculate the factorial of 1024, a larger value needs to be given to the maximum recursion depth. The following methods can be used here:
import sys sys.setrecursionlimit(5000) #修改为5000
In addition, you can also view the maximum recursion depth:
import sys sys.getrecursionlimit() # output:1000
The above is the detailed content of Python factorial sum method. For more information, please follow other related articles on the PHP Chinese website!