Python | Factorial of a number without Recursion

Method 1: Using the numpy library

import numpy

num = int(input("Enter a number whose factorial you want: "))  
if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
    x=numpy.prod([i for i in range(1,num+1)])
    print("The factorial of",num,"is",x)  

Output:

Enter a number whose factorial you want: 5
The factorial of 5 is 120

Explanation:

We simply used the prod() function of the numpy library, wherein we used a for loop that will run on till the number entered by the user.

Method 2: Directly using the factorial() of the math library

import math
 
def get_factorial(n):
    return(math.factorial(n))

num = int(input("Enter a number whose factorial you want: "))  

if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   print("The factorial of",num,"is",get_factorial(num))  

Output:

Enter a number whose factorial you want: 18
The factorial of 18 is 6402373705728000

Enter a number whose factorial you want: -89
Opps!, The number you entered is negative. Factorial does not exist for negative numbers

Method 3: Using iterative approach with range() function

def get_factorial(n):
    initial = 1
      
    for i in range(2, n+1):
        initial *= i
    return initial

num = int(input("Enter a number whose factorial you want: "))  

if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   print("The factorial of",num,"is",get_factorial(num))  

Explanation:

Here we assigned the value of initial * I to the variable initial. This simply means that as we start our for loop with 2, the very first value assigned to the initial will be 2*1 = 2. So at i=2, the value in the initial will be 2. This goes on till the loop reaches its defined range.

Method 4: Using simple iteration

def get_factorial(n):
    if n < 0:
        return 0
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact

num = int(input("Enter a number whose factorial you want: "))  

if num < 0:  
   print("Opps!, The number you entered is negative. Factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   print("The factorial of",num,"is",get_factorial(num))  

Here is the end of our article. We encourage you to come up with your approach and share it with us.

Share:

Author: Ayush Purawr