Open In App

Factorial of a Number - Python

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
264 Likes
Like
Report

The factorial of a number is the product of all positive integers less than or equal to that number. For example, the factorial of 5 (denoted as 5!) is 5 × 4 × 3 × 2 × 1 = 120. In Python, we can calculate the factorial of a number using various methods, such as loops, recursion, built-in functions, and other approaches.

Example: Simple Python program to find the factorial of a number


Output
720

Explanation: This code calculates the factorial of a number n (which is 6 in this case) using a for loop. It initializes the variable fact to 1. Then, it multiplies fact by each integer from 1 to n (inclusive) in the loop, updating the value of fact with each iteration. Finally, it prints the result, which is the factorial of 6 (720).

Using a Recursive Approach

This Python program uses a recursive function to calculate the factorial of a given number. The factorial is computed by multiplying the number with the factorial of its preceding number.


Output
120

Explanation: This approach calculates the factorial using recursion. The base case is when n is 0 or 1, in which case the factorial is 1. For any other number, the function calls itself, reducing the number until it reaches the base case.

Using math.factorial()

In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number.

Explanation: This code defines a function factorial(n) that uses Python's built-in math.factorial() function to calculate the factorial of a given number n. In the driver code, it calls this function with num = 5 and prints the result, which is the factorial of 5 (120).

Using numpy.prod()

This Python code calculates the factorial of n using NumPy. It creates a list of numbers from 1 to n, computes their product with numpy.prod(), and prints the result.


Output
120

Explanation: Here, the numpy.prod() function is used to compute the factorial. The list comprehension generates a list of numbers from 1 to n, and numpy.prod() calculates the product of all the elements in the list, which is equivalent to the factorial of the number.

Using Prime Factorization

This code calculates the factorial of a number by first finding the prime factors of each number from 2 to n, and then multiplying them together to compute the factorial. The prime factors are stored along with their powers for efficient multiplication.


Output
120

Explanation: This approach uses prime factorization to calculate the factorial. The primeFactors() function finds the prime factors of each number from 2 to n, and the factorial() function multiplies the factors accordingly.


Python Program to Find the Factorial of a Number
Next Article
Practice Tags :

Similar Reads