Ad
Algorithms
Logic
Mathematics
Numbers

For greater efficiency, I give you a lookup table that cuts down execution time by up to 40%!

6035ms from 10958ms

Code
Diff
  • def factorial(x):
        result = 1
        if len(factorial.lookup) <= x:
            factorial.lookup = [1] * (x + 1)
            for i in range(2, x + 1):
                result *= i
                factorial.lookup[i] = result
            return result
        return factorial.lookup[x]
    factorial.lookup = []
    • def factorial(x):
    • result = 1
    • for i in range(2, x + 1):
    • result *= i
    • return result
    • if len(factorial.lookup) <= x:
    • factorial.lookup = [1] * (x + 1)
    • for i in range(2, x + 1):
    • result *= i
    • factorial.lookup[i] = result
    • return result
    • return factorial.lookup[x]
    • factorial.lookup = []
Algorithms
Logic
Mathematics
Numbers
Code
Diff
  • def factorial(x):
        return x * factorial(x-1) if x > 0 else 1
    
    • def factorial(x):
    • result = 1
    • for i in range(2, x+1):
    • result *= i
    • return result
    • return x * factorial(x-1) if x > 0 else 1