How to find factorial recursively in Python

angryTom
Release: 2020-02-13 11:23:30
Original
21526 people have browsed it

How to find factorial recursively in Python

How to find factorial recursively in python

Factorial: For example, 5! refers to the "factorial of 5", that is, 5! = 1* 2*3*4*5.

"Recursion" is a function that calls itself.

Recommended learning:Python video tutorial

def f(x): if x == 0: return 0 elif x == 1: return 1 else: return (x * f(x-1)) print(f(5))
Copy after login

Code explanation: If x=5, then return the value of 5*f(4). If you want to know this value, you must first calculate what f(4) is equal to. According to the function f(x), f(4) = 4*f(3), so f(5) = 5*4*f(3). By analogy, f(5) = 5*4*3*2*f(1). Function f(x) says that when x==1, the return value is 1. So: f(5) = 5*4*3*2*1 = 120. Therefore, the output result is as follows:

120
Copy after login

It sounds very troublesome and hard to understand. What if we don’t use recursive functions? Using the most basic code, it can be written as:

f = 1 for i in range(1,6): f = f * i print(f)
Copy after login

The result is still 120.

The above is the detailed content of How to find factorial recursively in Python. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!