Python Program to Find Factorial of a Large Number



Before going to the solution let's understand about factorial. The factorial is a product of all the integers smaller than or equal to n. The mathematical representation is n!=n*(n -1)*(n-2)*(n-1)*....1 .For an example, 4! = 4*3*2*1 is 24.

In this article let's try to find the different ways to find the factorial of a large number.

Various Methods

Following are multiple ways to find the factorial of a large number in Python ?

  • Using 'math' Module
  • Using 'for' loop
  • Using 'array'

Using the 'math' Module to find factorial

The math module is a built-in Python module used for performing mathematical operations. This module provides various built-in methods for performing different mathematical tasks.

This module's methods do not work with complex numbers. For that, we can use the cmath module. Following is the syntax to import the math module ?

import math

By importing the math module we can find the factorial of a large number using the factorial() function.

Example

Following is an example of finding the factorial of a large number by importing math ?

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

n = 50
print("Factorial of ",n,":",solve(n))

Following is the output of the above code ?

Factorial of  50 : 30414093201713378043612608166064768844377641568960512000000000000

Using the 'for' loop to find factorial

The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple, or string. It performs the same action on each item of the sequence. This loop starts with the for keyword, followed by a variable representing the sequence's current item.

The in keyword links the variable to the sequence we want to iterate over. A colon(:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence. Following is the syntax of the for loop in Python ?

for iterating_var in sequence:
   statement(s)

We can find the factorial of a large number using a for loop. In this method, initialize fac with 1 and run the loop from 2 to N+1.

Example

In the following example we have found the factorial of a large number using for loop ?

def factorial(n):
    fact=1
    for i in range(2,n+1):
        fact=fact*i
        
    return fact
    
print("Factorial of 50 :",factorial(50))

Following is the output of the above code ?

Factorial of 50 : 30414093201713378043612608166064768844377641568960512000000000000

Using 'array' to find factorial

An array is a container that can hold a fixed number of items and these items should be of the same type. Each item stored in an array is called an element and can be of any type including integers, floats, strings, etc.

These elements are stored at contiguous memory locations. Each location of an element in an array has a numerical index starting from 0. These indices are used to identify and access the elements.

In Python, the array is not in-build to create an array we need to import an array module. Following is the syntax to create an array ?

import array as array_name
# creating array
obj = array_name.array(typecode[, initializer])

Using an array we can find the factorial of a large number. The algorithm contains two functions. Let us understand the steps of each function individually. Following is the algorithm of the factorial function ?

  • Create an array rev[] of max size, where max is a number of maximum digits in output.
  • Initialize the value stored in rev[] as 1 and rev_size as 1.
  • Multiply x with rev[] and update rev[] and rev_size to store the multiplication result for all the numbers from x = 2 to n.
  • To multiply a number x with the number stored in rev[], one by one multiply x with every digit of rev[].

Following are the steps to implement the multiply function ?

  • Initialize carry as 0.
  • Do following for i = 0 to [res_size - 1] ?
  • Find the value of rev[i] * x + carry. Let this value be prod.
  • Update rev[i] by storing the last digit of prod in it.
  • Update carry by storing the remaining digits in carry.
  • Put all digits of carry in res[] and increase res_size by the number of digits in carry.

Example

In the following example we have found the factorial of a large number using the array ?

import sys
def factorial(n):
    rev = [None]*500
    # Initialize result
    rev[0] = 1
    rev_size = 1

    # Apply simple factorial formula
    # n! = 1 * 2 * 3 * 4...*n
    x = 2
    while x <= n:
        rev_size = multiply(x, rev, rev_size)
        x = x + 1

    print("Factorial of given number is:")
    i = rev_size - 1
    while i >= 0:
        sys.stdout.write(str(rev[i]))
        sys.stdout.flush()
        i = i - 1

def multiply(x, rev, rev_size):
    carry = 0  # Initialize carry

    # One by one multiply n with individual digits of rev[]
    i = 0
    while i < rev_size:
        prod = rev[i] * x + carry
        rev[i] = prod % 10  # Store last digit of 'prod' in rev[]
        carry = prod // 10  # Put rest in carry
        i = i + 1

    # Put carry in rev and increase result size
    while carry:
        rev[rev_size] = carry % 10
        carry = carry // 10
        rev_size = rev_size + 1

    return rev_size

# Driver program
factorial(50)

Following is the output of the above code ?

Factorial of given number is:
30414093201713378043612608166064768844377641568960512000000000000
Updated on: 2025-01-22T13:36:57+05:30

688 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements