Factorial Calculator in Python

Factorial Calculator in Python

25 Nov 2024
Beginner
842 Views
11 min read
Learn with an interactive course and practical hands-on labs

Free Data Structures & Algorithms Online Course

Factorial Program in Python

The factorial program in Python is a common programming exercise for beginners and professionals alike. It involves calculating the factorial of a number, which is the product of all positive integers up to that number.
In this Python Tutorial, we’ll explore various methods to write a factorial program in Python using for loop, while loop, recursion, and functions. We will also discuss how to write a factorial program without functions and how to take user input for more dynamic results.

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

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

Factorial Program in Python provides another way to calculate the factorial of a number. It continues executing as long as a specified condition is true. This method can be particularly useful when the number of iterations isn’t predetermined:

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

In Python, recursion is a powerful tool for solving factorial problems elegantly. A factorial program in Python using recursion defines a function that calls itself to compute the result. This approach mimics the mathematical definition of a factorial:

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 Function

Writing a factorial program in Python using a function helps encapsulate the logic in a reusable block of code. Whether you’re using loops or recursion, defining a function enhances code readability and reusability.

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

7. Using For Loop

The for loop iteratively multiplies numbers in a sequence. Here’s how to calculate the factorial of a number using a for loop:



def factorial_for_loop(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
           
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

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

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.

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.

An example of a factorial is 5!, which equals 5×4×3×2×1-=120
Share Article
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