Recursive Factorial with Memoization

  • Share this:

Code introduction


Calculates the factorial of a given non-negative integer using recursion and memoization to optimize performance.


Technology Stack : Recursion, memoization, dictionary

Code Type : Function

Code Difficulty : Intermediate


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