How to Write a Python Program to Find the Sum of Factorials Using Recursion?

Estimated read time 2 min read

To write a Python program to find the sum of factorials using recursion, you can define a recursive function that calculates the factorial of a given number. Then, within another recursive function, you can sum the factorials of consecutive numbers up to a given limit. Here’s an example:

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

def sum_of_factorials(n):
    if n == 0:
        return 0
        return factorial(n) + sum_of_factorials(n - 1)

limit = 5
result = sum_of_factorials(limit)
print(f"The sum of factorials up to {limit} is: {result}")

In this example, we define two recursive functions. The factorial(n) function calculates the factorial of a given number n by recursively multiplying n with the factorial of n-1. The base case is when n reaches 0, where the factorial is defined as 1.

The sum_of_factorials(n) function recursively calculates the sum of factorials up to a given number n. It does this by calling the factorial(n) function for each number from n down to 1 and summing the results. The base case is when n reaches 0, where the sum is defined as 0.

In the example, we set the limit to 5 and call the sum_of_factorials(limit) function to calculate the sum of factorials up to 5. The result is then printed.

Note that calculating factorials using recursion can be computationally expensive for larger numbers due to the repeated calculations. Consider using iterative approaches or memoization techniques for optimizing factorial calculations in real-world scenarios.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply