Optimized Recursive Factorial with Caching

  • Share this:

Code introduction


Calculates the factorial of an integer using recursion and caching to optimize performance.


Technology Stack : Recursion, Caching

Code Type : Function

Code Difficulty : Intermediate


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