Home > Backend Development > Python Tutorial > Python finds the factorial of n

Python finds the factorial of n

Release: 2019-10-25 09:55:33
Original
59860 people have browsed it

Python finds the factorial of n

Factorial is an arithmetic symbol invented by Christian Kramp (1760-1826) in 1808. It is a mathematical term. The factorial of a positive integer is the product of all positive integers less than or equal to that number, and the factorial of 0 is 1. The factorial of a natural number n is written n!.

Let’s take a look at how to use Python to calculate the factorial of n:

The first one: use the functools tool to process

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(5)
print(result)```
Copy after login

The second one: ordinary loops

x = 1
y = int(input("请输入要计算的数:"))
for i in range(1, y + 1):
   x = x * i
print(x)
Copy after login

The third way: using recursion

def func(n):
    if n == 0 or n == 1:
        return 1
    else:
        return (n * func(n - 1))
 a = func(5)
 print(a)
Copy after login

Recommended: "python tutorial"

The above is the detailed content of Python finds the factorial of n. 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