+1

# Factorial help

Hello! I've got a task to list first 100 factorial numbers iterative and recursive. This is my attempt for the recursive code, but it doesn't seem to get the output my teacher wants. def faktor(n): faktor = (n + 1) * n if n <= 0: return n else: return (n + 1) * n print(faktor(100)) I've also tried with n-1 Can you give me some advice to make it work? Thank you!

5/13/2021 6:33:46 AM

Kajtár László

+3

Correct answer: ————————— def fact(n) : if n == 1: return n else: return n*fact(n-1) num = int(input()) if num==0: print(1) elif num<0: print("fact not exists") else: print(fact(num))

+3

Thank you all! I've managed to solve it!

+3

Wanna see the twisted one, it's fast too def factorial(n): return eval("*".join(map(str,range(1,n+1)))) also added the code here: https://code.sololearn.com/c6K7HkxeJARv/?ref=app

+2

Def fact(nb): if nb == 1: return nb return nb * fact(n-1)

+2

Iterative Approach ___________________ f = 1 n = int(input()) if n==0: print(1) elif n<0: print("fact not exists") else: while n!=0: f *= n n -= 1 print(f) Recursive Approach ____________________ def fact(n) : if n == 1: return n else: return n*fact(n-1) num = int(input()) if num==0: print(1) elif num<0: print("fact not exists") else: print(fact(num))

+1

Here's the iterative approach: n = 1 for i in range(100): print(n := (n * (i + 1))) Here's the recursive approach: def fact(n): if n < 2: return n return fact(n - 1) * n for i in range(100): print(fact(i)) # Hope this helps I'd prefer to use the iterative approach, as the latter one is memory-inefficient and comparatively more complex.