Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Factorial Calculator in Python

Factorial Calculator in Python

03 Jul 2024
Beginner
1.75K Views
9 min read

What is factorial?

The factorial of a number is the multiplication of all the numbers between 1 and the number itself. It is a mathematical operation written like this: n!. It's a positive integer. Factorial is not defined for negative numbers.

For example, the factorial of 3 is 3! (= 1 × 2 x 3).

In this Python tutorial, we'll learn the various methods to calculate the factorial of a number in Python.

Read More: Top 50 Python Interview Questions and Answers

How to calculate the factorial of a number in Python?

1. Using While Loop/Iterative approach


def factorial(n):
    if n < 0:
           print("Sorry, factorial is undefined for negative numbers")
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact

num = 8
print("Factorial of",num,"is",
factorial(num))   

In the above code, we check if the number is negative, zero, or positive using the if...elif...else statement. If the number is positive, we use the while loop in python to calculate the factorial.

iterationfact*i (returned value)
18*1=8
28*7=56
356*6=336
4336*5=1680
51680*4=6720
66720*3=20160
720160*2=40320
840320*1=40320

Output

Factorial of 8 is 40320

2. Using Recursion


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))

In the above code, factorial() is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the num.

Output

Factorial of 8 is 40320
Read More: Recursion in Data Structures

3. Using One line Solution (Using Ternary operator)


def factorial(n):

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

num = 8
print ("Factorial of",num,"is",
      factorial(num))

Output

Factorial of 8 is 40320
Read More: What are Operators in Python?

4. Using Built-In Function


import math

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

num = 8
print("Factorial of", num, "is",
      factorial(num))

In the above code, we've used the math module that contains the math.factorial() function to calculate the factorial of any given number.

Output

Factorial of 8 is 40320
Read More: Python Functions - A Complete Guide

5. Using numpy.prod


import numpy
num=8
fact=numpy.prod([i for i in range(1,num+1)])
print("Factorial of", num, "is",
      fact)

In the above code, we've used the numpy module that contains the numpy.prod() function to calculate the factorial of any given number.

Output

Factorial of 8 is 40320

6. Using the Prime Factorization Method


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

num = 8
print("Factorial of", num, "is", factorial(num))

In the above code,

  1. First, initialize the factorial variable to 1.
  2. For each number i from 2 to n:
    1. Find the prime factorization of i.
    2. 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.

Output

Factorial of 8 is 40320
Read More:
Summary

In the above tutorial, we learned various methods to calculate the factorial of a number in Python. Before trying these methods, you must be clear with the fundamental concepts of loops, recursion, modules, functions, etc. Just refer to these tutorials and come back to learn factorial calculation in Python.

FAQs

Q1. How do you code a factorial in Python?

You can code a factorial in Python using recursion, iteration, ternary operator, 
built-In function, numpy.prod, and prime factorization method.

Q2. What is the logic of factorial?

Factorial logic involves multiplying a number by all positive integers less than itself, recursively reducing the problem until reaching the base case of factorial(1) = 1.

Q3. What is the factorial formula in programming?

The factorial formula in programming is typically expressed as n!=n×(n−1)×(n−2)×…×1, where n is a non-negative integer. It represents the product of all positive integers from 1 to 𝑛, inclusive.

Q4. What is an example of a factorial?

An example of a factorial is 5!, which equals 5×4×3×2×1-=120
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Full-Stack .NET Developer Certification TrainingOct 13SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this