The Wayback Machine - https://web.archive.org/web/20250118021434/https://www.geeksforgeeks.org/python-program-for-factorial-of-a-number/
Open In App

Python Program to Find the Factorial of a Number

Last Updated : 23 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n in Python. 

Example

Simple Python program to find the factorial of a number

Python
# Input: An integer number
num = 6

# Initialize the factorial variable to 1
factorial = 1

# Calculate the factorial using a for loop
for i in range(1, num + 1):
    factorial *= i

# Output: The factorial of the number
print(f"The factorial of {num} is {factorial}")

Output

The factorial of 6 is 720

Get Factorial of a Number 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.

python
# Python 3 program to find 
# factorial of given number
def factorial(n):
    
    # single line to find factorial
    return 1 if (n==1 or n==0) else n * factorial(n - 1) 

# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))

Output:

Factorial of 5 is 120

Time Complexity: O(n)
Auxiliary Space: O(n)

Find Factorials quickly using One liner (Using Ternary Operator)

This Python function calculates the factorial of a number using recursion. It returns 1 if n is 0 or 1; otherwise, it multiplies n by the factorial of n-1.

Python
def factorial(n):

    # single line to find factorial
    return 1 if (n==1 or n==0) else n * factorial(n - 1) 


# Driver Code
num = 5
print ("Factorial of",num,"is",
      factorial(num))

Output:

Factorial of 5 is 120

Time Complexity: O(n)
Auxiliary Space: O(n)

Factorial Function in Maths

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.

Python
# Python 3 program to find
# factorial of given number
import math

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


# Driver Code
num = 5
print("Factorial of", num, "is",
      factorial(num))

# This code is contributed by Ashutosh Pandit

Output:

Factorial of 5 is 120

Time complexity: O(N)
Auxiliary space: O(1)

Find the Factorial of a Number Using NumPy

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.

Python
import numpy
n=5
x=numpy.prod([i for i in range(1,n+1)])
print(x)

Output 

120

Time Complexity: O(n)
Auxiliary Space: O(1)

Prime Factorization Method to find Factorial

  1. Initialize the factorial variable to 1.
  2. For each number i from 2 to n, do the following:
    a. Find the prime factorization of i.
    b. For each prime factor p and its corresponding power k in the factorization of i, multiply the factorial variable by p raised to the power of k.
  3. Return the factorial variable.
Python
# Function to find prime factors of a number
def primeFactors(n):
    factors = {}
    i = 2
    while i*i <= n:
        while n % i == 0:
            if i not in factors:
                factors[i] = 0
            factors[i] += 1
            n //= i
        i += 1
    if n > 1:
        if n not in factors:
            factors[n] = 0
        factors[n] += 1
    return factors

# Function to find factorial of a number
def factorial(n):
    result = 1
    for i in range(2, n+1):
        factors = primeFactors(i)
        for p in factors:
            result *= p ** factors[p]
    return result

# Driver Code
num = 5
print("Factorial of", num, "is", factorial(num))

Output
Factorial of 5 is 120

Time Complexity: O(sqrt(n))
Auxiliary Space: O(sqrt(n))

Please refer complete article on Program for factorial of a number for more details!


Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg