educative.io

Educative

Any other solutions?

Could anyone share the solution that does not use recursion?

def factorial(n):
# Base case
if n == 0 or n == 1:
return 1

if n < 0:
    return -1
# Recursive call
return n * factorial(n - 1)

print(factorial(5))


Course: https://www.educative.io/collection/10370001/5473789393502208
Lesson: https://www.educative.io/collection/page/10370001/5473789393502208/6334488760025088

Hey @SCC!
You can use this code for finding factorials without using recursion.

def factorial(n):
      fact=1
      if n<0:
         return -1
      else:
         for i in range(1,n+1):
            fact=fact * i
         return fact
1 Like

Thank you, for loop is a way to go :slight_smile: