Home  >  Article  >  Backend Development  >  How to calculate the factorial of n in python

How to calculate the factorial of n in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-10-25 13:45:5926936browse

How to calculate the factorial of n in python

The factorial of an integer (English: factorial) is the product of all positive integers less than and equal to the number, 0 The factorial is 1. That is: n!=1×2×3×...×n.

First import the math module, and then call the factorial() function to calculate the factorial.

Related recommendations: "Python Basic Tutorial"

1 math.factorial(x)

import math
value = math.factorial(x)

2. reduce function

def factorial(n):
    return reduce(lambda x,y:x*y,[1]+range(1,n+1))

3. Recursive implementation

def factorial(n):    
    if n == 0:        
        return 1    
    else:        
        return n * factorial(n - 1)

The above is the detailed content of How to calculate the factorial of n in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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