The Wayback Machine - https://web.archive.org/web/20240821091404/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 : 30 Jul, 2024
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. 

For example factorial of 6 is 6*5*4*3*2*1 which is 720.

Find the Factorial of a Number Using 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 the Factorial of a Number Using Iterative approach

Example 1:

python
# Python 3 program to find  
# factorial of given number
def factorial(n):
    if n < 0:
        return 0
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact

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

# This code is contributed by Dharmik Thakkar

Output:

Factorial of 5 is 120

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

Example 2: 

Python
# Python 3 program to find
# factorial of given number
 
# Function to find factorial of given number
def factorial(n):
      
    res = 1
     
    for i in range(2, n+1):
        res *= i
    return res
 # Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))

Output
Factorial of 5 is 120

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

Find the Factorial of a Number Using One line Solution (Using Ternary operator): 

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

# This code is contributed
# by Smitha Dinesh Semwal.

Output:

Factorial of 5 is 120

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

Find the Factorial of a Number Using using In-built function 

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.

Syntax: math.factorial(x)

Parameter:
x: This is a numeric expression.

Returns:  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.prod 

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
# Python 3 program to find factorial
# of a given number using prime
# factorization method.

# 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!



Previous Article
Next Article

Similar Reads

Find the last digit when factorial of A divides factorial of B
We are given two numbers A and B such that B &gt;= A. We need to compute the last digit of this resulting F such that F = B!/A! where 1 = A, B &lt;= 10^18 (A and B are very large).Examples: Input : A = 2, B = 4Output : 2Explanation : A! = 2 and B! = 24. F = 24/2 = 12 --&gt; last digit = 2Input : 107 109Output : 2As we know, factorial function grows
10 min read
Python program to find the factorial of a number using recursion
A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n. [Tex]n! = n*(n-1)*(n-2)*(n-3)*....*1 [/Tex] For example: [Tex]5! = 5*4*3*2*1 = 120 [/Tex] In this article, we are going to calculate the factorial of a number using recursion. Examples: Input: 5 Output: 120 Input: 6 Output: 720 I
1 min read
Recursive Program to find Factorial of a large number
Given a large number N, the task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 933262154439441526816992388562667004-907159682643816214685929638952175999-9322
6 min read
Python Program to Count trailing zeroes in factorial of a number
Given an integer n, write a function that returns the count of trailing zeroes in n! Examples : Input: n = 5 Output: 1 Factorial of 5 is 120 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5
4 min read
Golang Program to Count Trailing Zeros in Factorial of a Number
Given an integer n, write a Go program to count the number of trailing zeros in the factorial of n. Examples: Input : 7 Output : 1 Explanation: 7! = 5040, which has 1 trailing zero Input : 10 Output : 2 Explanation: 10! = 3628800, which has 2 trailing zeros Naive approach: To count the trailing zeros in n!, one approach is to find the factorial of
3 min read
Program for factorial of a number
Given the number N (N &gt;=0), print its factorial. Factorial of a non-negative integer is the multiplication of all positive integers smaller than or equal to N. It is represented by a number and a ”!” mark at the end and is widely used in permutations and combinations to calculate the total possible outcomes. Examples: Input: 5Output: 120Explanat
7 min read
Find remainder when a number A raised to N factorial is divided by P
Given three integers A, N and P, the task is to find (A^(N!)) % P. Examples: Input: A = 2, N = 1, P = 2Output: 0Explanation: As (2^(1!)) = 2 Therefore 2 % 2 will be 0. Input: A = 3, N = 3, P = 2Output: 1 Naive Approach: The simplest solution of this problem can be find out factorial of N say f, and now calculate A to power f say pow and find its re
10 min read
Find sum of digits in factorial of a number
Given a number n, write code to find the sum of digits in the factorial of the number. Given n ≤ 5000 Examples: Input : 10 Output : 27 Input : 100 Output : 648 Recommended PracticeSum of digits in factorial of a numberTry It!It is not possible to store a number as large as 100! under some data types so, idea is to store an extremely large number in
11 min read
Find the first natural number whose factorial is divisible by x
Given a number x, the task is to find first natural number i whose factorial is divisible by x.Examples : Input : x = 10 Output : 5 5 is the smallest number such that (5!) % 10 = 0 Input : x = 16 Output : 6 6 is the smallest number such that (6!) % 16 = 0 A simple solution is to iterate from 1 to x-1 and for every number i check if i! is divisible
14 min read
Find the last two digits of Factorial of a given Number
Given an integer N, the task is to find the last two digits of factorial of a number. Examples: Input: N = 7 Output: 40 Explanation: 7! = 5040Input: N = 11 Output: 00 Approach#1We can observe that for N &gt;= 10, the last two places of its factorial will contain 0's only. Hence N! % 100 for any N &gt;= 10 will always be 0. So we just calculate the
15 min read
Find maximum power of a number that divides a factorial
Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples: Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s formula which finds largest power of a prime numbe
12 min read
Find the Factorial of a large number
Find the factorial of a large number.  What is Factorial of a number?Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n.  Examples:  Input: 100Output: 933262154439441526816992388562667004-         907159682643816214685929638952175999-         932299156089414639761565182862536979-         2082722375
15+ min read
Find the length of factorial of a number in any given base
Given an integer n and base B, the task is to find the length of n! in base B.Examples: Input: n = 4, b = 10 Output: 2 Explanation: 4! = 24, hence number of digits is 2 Input: n = 4, b = 16 Output: 2 Explanation: 4! = 18 in base 16, hence number of digits is 2 Brute Force Approach: The brute force approach to solve this problem would involve findin
9 min read
Check if a given number is factorial of any number
Given a number n, the task is to determine whether n can be a factorial of some number x.Examples: Input: N = 24Output: YesExplanation: 4! = 24 Input: N = 25Output: No Approach: For a number to be a factorial of any number it must be divisible by all the numbers from 1 to that number. So in this approach We keep on dividing the number if it is comp
4 min read
Find GCD of factorial of elements of given array
Given an array with N positive integers. Find the GCD of factorials of all elements of array.Examples: Input : arr[] = {3, 4, 8, 6} Output : 6 Input : arr[] = {13, 24, 8, 5} Output : 120 Approach: To find the GCD of factorial of all elements, first of all, calculate the factorial of all elements and then find out their GCD. But this seems to be a v
5 min read
Find the next Factorial greater than N
Given a number N (? 1018), the task is to find the next factorial number greater than N.Examples: Input: N = 24 Output: 120 Explanation: As 4! = 24. So the next number which factorial and greater than 24 is 5!, which is 120Input: N = 150 Output: 720 Explanation: As 5! = 120. So the next number which factorial and greater than 150 is 6!, which is 72
5 min read
Find sum of factorials till N factorial (1! + 2! + 3! + ... + N!)
Given a positive integer N. The task is to compute the sum of factorial from 1! to N!, 1! + 2! + 3! + ... + N!. Examples: Input: N = 5Output: 153Explanation: 1! + 2! + 3! + 4! + 5! = 1 + 2 + 6 + 24 + 120 = 153. Input: N = 1Output: 1 Naive Approach: The basic way to solve this problem is to find the factorial of all numbers till 1 to N and calculate
8 min read
Find all factorial numbers less than or equal to n
A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are1, 2, 6, 24, 120, ...Given a number n, print all factorial numbers smaller than or equal to n. Examples : Input: n = 100Output: 1 2 6 24 Input: n = 1500Output: 1 2 6 24 120 720 A simple solution is to generate all fa
6 min read
Find last digit in factorial
Given a number n, we need to find the last digit in factorial n. Input : n = 4Output : 44! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4. Input : n = 5Output : 55! = 5*4 * 3 * 2 * 1. = 120. Last digit of 120 is 0. A Naive Solution is to first compute fact = n!, then return the last digit of the result by doing fact % 10. This solution is inefficient
7 min read
One line function for factorial of a number
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. Example : Factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. We can find the factorial of a number in one line with the help of Ternary operator or commonly known as Conditional operator in recursion. C/C++ Code // C++ program to find factorial of
3 min read
First digit in factorial of a number
Given a positive integer n, find the first digit in its factorial. Examples : Input : n = 5 Output : 1 Factorial of 5 is 120 and first digit is 1. Input : 1000 Output : 4 A simple solution is to compute factorial of number, then find first digit in it. The above solution causes overflow soon. A better solution is to use the fact that factorial cont
5 min read
Number of digits in N factorial to the power N
Given a positive integer N, we have to find the total number of digits in the factorial of N raised to the power N, i.e, [Tex](N!)^N [/Tex]Examples: Input: 4 Output: 6 Explanations: [Tex](4!)^4[/Tex] = [Tex](24)^4[/Tex] = 331776. Total number of digits in 331776 is 6.Input: 5Output: 11Explanations: [Tex](5!)^5[/Tex] = [Tex](120)^5[/Tex] = 248832000
4 min read
Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Factorial of a number without using multiplication
Given a positive number N, the task is to calculate the factorial of N without using the multiplication operator. Examples: Input: N = 5Output:120Explanation:5*4*3*2*1=120 Input: N = 7Output:5040 Observation: A*B=A+A+A+A...B times. This observation can be used as follows: 5!=5*4*3*2*1 =(5+5+5+5)*3*2*1 =(20+20+20)*2*1 =60+60 =120 Approach 1: The pro
7 min read
Calculate MDAS Factorial of given number
Given an integer N, the task is to find the MDAS factorial.The general factorial of a no. N is given by: Factorial(N) = (N)*(N-1)*(N-2)*(N-3)*(N-4)*(N-5)*(N-6)*(N-7)- - - - - -(3)*(2)*(1). In MDAS factorial, instead of simply multiplying the numbers from N to 1, we perform four operations, Multiplication(*), Divide(/), Addition(+) and Subtraction(-
5 min read
Smallest number with at least n trailing zeroes in factorial
Given a number n. The task is to find the smallest number whose factorial contains at least n trailing zeroes.Examples : Input : n = 1Output : 5 1!, 2!, 3!, 4! does not contain trailing zero.5! = 120, which contains one trailing zero.Input : n = 6Output : 25Recommended PracticeSmallest factorial numberTry It!Approach:In this approach, we use a whil
9 min read
Smallest number with at least n digits in factorial
Given a number n. The task is to find the smallest number whose factorial contains at least n digits.Examples: Input : n = 1 Output : 0 0! = 1, hence it has 1 digit. Input : n = 2 Output : 4 4! = 24 and 3! = 6, hence 4 is the smallest number having 2 digits in its factorial Input : n = 5 Output : 8 In the article for Count digits in a factorial of
10 min read
Sum of divisors of factorial of a number
Given a number n, we need to calculate the sum of divisors of factorial of the number. Examples: Input : 4 Output : 60 Factorial of 4 is 24. Divisors of 24 are 1 2 3 4 6 8 12 24, sum of these is 60. Input : 6 Output : 2418 A Simple Solution is to first compute the factorial of the given number, then count the number divisors of the factorial. This
14 min read
Smallest number S such that N is a factor of S factorial or S!
Given a number N. You are tasked with finding the smallest number S, such that N is a factor of S! (S factorial). N can be very large.Examples: Input : 6 Output : 3 The value of 3! is 6 This is the smallest number which can have 6 as a factor. Input : 997587429953 Output : 998957 If we calculate out 998957!, we shall find that it is divisible by 99
9 min read
Count trailing zeroes in factorial of a number
Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5Output: 1 Explanation: Factorial of 5 is 120 which has one trailing 0. Input: n = 20Output: 4Explanation: Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100Output: 24 Table of Content [Naive Approach] By calculati
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg