Recursive Factorial Calculation with Caching

  • Share this:

Code introduction


This function calculates the factorial of an integer using recursion and uses a cache (dictionary) to store previously computed results for efficiency.


Technology Stack : Recursion, dictionary, caching

Code Type : Recursive function

Code Difficulty : Intermediate


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