Recursive Factorial with Caching Optimization

  • Share this:

Code introduction


This function calculates the factorial of an integer using recursion and caching to optimize performance.


Technology Stack : Recursion, caching

Code Type : Recursive function

Code Difficulty : Intermediate


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