PYTHON: How to get factorial by recursion

Spread the love

1. The concept of factorial

The factorial of a positive integer is the product of all positive integers less than and equal to the number, and the factorial of 0 is 1. The factorial of a natural number n is written as n!. It is invented by Christan Kramp (1760-1826)

That is, n!=1×2×3×…×n. Factorials can also be defined recursively: 0!=1, n!=(n-1)!×n.

2. The concept of recursion

The programming technique by which a program calls itself is called recursion. Recursion as an algorithm is widely used in programming languages.
A procedure or function in its definition or description has a method of directly or indirectly calling itself, which usually transforms a large and complex problem into a smaller problem similar to the original problem to solve. In the recursive strategy, only a small number of programs can be used to describe the repeated calculations required for the problem-solving process, which greatly reduces the code amount of the program. The power of recursion lies in defining infinite sets of objects with finite statements. In general, recursion requires boundary conditions, recursive forward segments, and recursive return segments. When the boundary conditions are not satisfied, the recursion proceeds; when the boundary conditions are satisfied, the recursion returns.

3. Source Code

def factCal(i):
    if i==1:
        return 1
    else:
        return i*factCal(i-1)
    
print('Factorial Calculator')
factNum=int(input('The factorial num is '))

if factNum==0:
    print('0!=1')
else:
    print(str(factNum)+'!='+ str(factCal(factNum)))

4. Running Result

5. Note

The recursive method to solve the problem can easily lead to memory overflow if we don’t set up the condition carefully.

Zeren
If you want to know more about me, please get on the about page. :)
Posts created 18

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
error: Content is protected !!