+ 2

How to do factorial in python

2nd Aug 2019, 3:45 AM
kishor kiss
kishor kiss - avatar
3 Answers
+ 6
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) Or you can use the factorial() function from the math module from math import factorial
2nd Aug 2019, 3:48 AM
Mikhail Gorchanyuk
Mikhail Gorchanyuk - avatar
+ 2
No recursion needed: x = 1 for i in range(1, 5): x *= i print(x) #120
2nd Aug 2019, 2:05 PM
Seb TheS
Seb TheS - avatar
+ 1
I would add to the answer above memoization by adding an array that store factorials already found.
2nd Aug 2019, 10:20 AM
DonPietro Cavastano
DonPietro Cavastano - avatar