Home  >  Article  >  Backend Development  >  How to find the factorial of an integer n in python?

How to find the factorial of an integer n in python?

青灯夜游
青灯夜游Original
2020-07-23 15:19:3021503browse

Python method to find the factorial of an integer n: 1. First import the math module, and then use math.factorial(n) to calculate the factorial of n; 2. Use the reduce() function to find the factorial; 3. Through recursion Let’s find the factorial.

How to find the factorial of an integer n in python?

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

1. Use math.factorial(x)

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

import math
 
value = math.factorial(x)

2. Use the 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)

Recommended learning: Python video Tutorial

The above is the detailed content of How to find the factorial of an integer 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