0
factorial of a series of first n natural number not using function
4 Answers
+ 3
While loop version:
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
Recursive version:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
+ 2
# for loop
a=1
n=3 ## change this
for i in range(n):
a *= (i+1)
print(a)
# list comprehension
n=4 ## change this
>>> [j for j in [1] for i in range(n) for j in [j * (i+1)]][-1]
Explanation:
Initialize j to 1 (so last multiply works)
Iterate i from 0..n-1
Build a list, appending as the last element the accumulator (last value of j) * (i-1).
Cut /display the last element (at index -1)
Possible disadvantage: This saves all the intermediate products, only clipping off the last product at the end. The for loop solution just keeps the running total.
0
Actually, pure recursive version will be slow, so here comes to place memoization, it makes it much faster.
0
jola