Recursive Factorial Calculation with Caching

  • Share this:

Code introduction


This function uses recursion to calculate the factorial of an integer. It uses a cache dictionary to store already computed results to avoid redundant calculations.


Technology Stack : Recursion, Caching

Code Type : Recursive function

Code Difficulty : Intermediate


                
                    
def factorial(n, cache=None):
    if cache is None:
        cache = {}
    if n in cache:
        return cache[n]
    if n == 0:
        return 1
    else:
        cache[n] = n * factorial(n - 1, cache)
        return cache[n]