Home > Backend Development > Python Tutorial > Python factorial sum method

Python factorial sum method

angryTom
Release: 2020-02-14 10:08:31
Original
18634 people have browsed it

Python factorial sum method

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()
Copy after login

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()
Copy after login

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
Copy after login

In addition, you can also view the maximum recursion depth:

import sys
sys.getrecursionlimit()  # output:1000
Copy after login

The above is the detailed content of Python factorial sum method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template