Recursive Factorial with Caching

  • Share this:

Code introduction


This function calculates the factorial of a number using recursion and employs caching to enhance performance.


Technology Stack : Built-in functions, recursion, caching

Code Type : Recursively Calculate Factorial

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)
    return _cache[n]