+ 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!

13th May 2021, 6:33 AM
KajtĂĄr LĂĄszlĂł
KajtĂĄr LĂĄszlĂł - avatar
6 Answers
+ 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))
13th May 2021, 7:37 AM
E.SANTHOSH
E.SANTHOSH - avatar
+ 3
Thank you all! I've managed to solve it!
13th May 2021, 9:56 AM
KajtĂĄr LĂĄszlĂł
KajtĂĄr LĂĄszlĂł - avatar
+ 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
14th May 2021, 4:55 AM
Geekyorion
+ 2
Def fact(nb): if nb == 1: return nb return nb * fact(n-1)
13th May 2021, 6:40 AM
Alpha Diallo
Alpha Diallo - avatar
+ 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))
13th May 2021, 7:00 AM
sarada lakshmi
sarada lakshmi - avatar
+ 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.
13th May 2021, 6:14 PM
Calvin Thomas
Calvin Thomas - avatar