Python Program to Find the Factorial of a Number

Problem Description

Write a Python Program to find the factorial of a number. If number is negative print the message otherwise find the factorial of the number.

What is Factorial of a Number?

Factorial of a number is the product of all positive integers from 1 to that number. It is denoted by the symbol “!”. For example, factorial of 5 is 5! = 5*4*3*2*1 = 120 and factorial of 8 is 8! = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 which equals to 40320.

By default, the factorial of 0 is 1, and the Factorial of a negative number is not defined.

In mathematics, a factorial is denoted by “!“. Therefore, the factorial of n is given by the formula
n! = n x (n-1) x (n-2) x (n-3) … x1.

Problem Solution

There are multiple methods to calculate the factorial of a number in Python. Let’s explore various approaches to implement this function:

Method 1: Factorial in Python using While Loop (Without Recursion)

In this method we run a while loop for N times and multiply all the N positive numbers.

advertisement
advertisement
Program/Source Code

Here is source code of the Python Program to calculate the factorial of a number using a while loop.

# Python program to find the factorial of a given number using while loop.
 
n=int(input("Enter number:"))
fact=1
while(n>0):
    fact=fact*n
    n=n-1
print("Factorial of the number is: ")
print(fact)
Program Explanation

1. The program initializes the factorial variable to 1.
2. Then, it enters a while loop and checks if the number is greater than 0.
3. If it is, the program multiplies the number by the factorial variable & decrements the number by 1.
4. The program repeats this process until the number is no longer greater than 0. At this point, the factorial variable contains the factorial of the number.

Time Complexity: O(n)
The time complexity of the above code is O(n) because the while loop iterates n times, where n is the input number.

Note: Join free Sanfoundry classes at Telegram or Youtube

Space Complexity: O(1)
The space complexity is O(1) because the code only uses a constant amount of additional space to store the factorial value.

Runtime Test Cases

Test case 1: Here is the runtime output of a Python program to find the factorial of a number when the user enters the number “5”.

Enter number: 5
Factorial of the number is: 
120

Test case 2: In this case, we input the number “4” to calculate its factorial.

Enter number: 8
Factorial of the number is: 
40320

advertisement
Method 2: Factorial in Python using Recursion

This program implements the factorial function in Python using recursion. It takes a number as input, calculates its factorial using recursive calls, and displays the result.

Program/Source Code

Here is source code of the Python Program to find the factorial of a number using recursion. The program output is also shown below.

# Python program to find the factorial of a number using Recursion
 
def factorial(n):
    if(n <= 1):
        return 1
    else:
        return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial of a Number is:")
print(factorial(n))
Program Explanation

1. The program defines a recursive function called factorial().
2. The function takes a number as input and returns the factorial of that number.
3. The base case of the recursive function is when the number is equal to 1 or 0.
4. In this case, the function returns 1.
5. Otherwise, the function returns the number multiplied by the factorial of the number minus 1.

advertisement

Time Complexity: O(n)
The time complexity of the above code is O(n) because the recursive function is called n times, where n is the input number.

Space Complexity: O(n)
The space complexity is O(n) as well because each recursive call adds a new frame to the call stack, which requires additional space proportional to the input number.

Runtime Test Cases

Here is the runtime output of a Python program to find the factorial of a number when the number entered by the user is “9”.

 
Enter number: 9
Factorial of a Number is 362880

Method 3: Factorial in Python using Function

In this method, the program uses a function called factorial() to calculate the factorial of a number. The factorial() function is implemented using the math.factorial() function.

Program/Source Code

Here is source code of the Python Program to find the factorial of a number using function. The program output is also shown below.

# Python program to find the factorial of a number using Function.
 
import math
 
def factorial(n):
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    else:
        return math.factorial(n)
 
# Prompt the user to enter a number
number = int(input("Enter a number: "))
 
# Calculate the factorial of the number
factorial = factorial(number)
 
# Print the factorial of the number
print("The factorial of {} is {}.".format(number, factorial))
Program Explanation

The program imports the math module and uses the math.factorial() function to calculate the factorial of the number. The math.factorial() function raises a ValueError exception if the input number is negative.

Time complexity: O(1)
The time complexity of the factorial() function is O(1) because it simply calls the math.factorial() function, which is a constant-time operation.

Space complexity: O(1)
The space complexity of the factorial() function is O(1) because it only uses a constant amount of additional space to store the factorial value.

Program Output:

In this case, we enter the number “5” as input to calculate its factorial.

Enter a number: 5
The factorial of 5 is 120.
Using the Factorial Function to Solve Real-World Problems.

Here are a few examples of how to use the factorial function to solve real-world problems:

  • Calculating the number of ways to arrange n objects in a row: The number of ways to arrange n objects in a row is n!. For example, there are 5! = 120 ways to arrange 5 objects in a row.
  • Calculating the number of ways to choose k objects from a set of n objects: The number of ways to choose k objects from a set of n objects is n!/k!(n-k)!. For example, there are 5C3 = 5!/3!(5-3) = 10 ways to choose 3 objects from a set of 5 objects.

Conclusion:

Factorials are an important mathematical concept with many applications in the real world. The Python programs presented in this document can be used to calculate the factorial of a number using a while loop, recursion, or a function.

To practice programs on every topic in Python, please visit “Programming Examples in Python”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.