Recursive Factorial with Caching

  • Share this:

Code introduction


This function calculates the factorial of a non-negative integer using recursion and caching techniques to optimize performance.


Technology Stack : Recursion, caching technique

Code Type : Recursive function

Code Difficulty : Intermediate


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