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

Program for factorial of a number

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
40.58%
1.4L

Given the number N (N >=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: 5
Output: 120
Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120

Input: 4
Output: 24
Explanation: 4! = 4 * 3 * 2 * 1 = 24

[Naive Approach] Using recursion – O(N) Time and O(N) Space

Intuition: Let’s try to observe some pattern:

N! = N * (N – 1) * (N – 2) …. 2 * 1

(N – 1)! = (N – 1) * (N – 2) … 2 * 1

From the above two equations, we can say that N! = N * (N – 1)!

Approach:

Since the problem can be broken down into The idea is to define a recursive function, say factorial(N) to calculate the factorial of number n. According to the value of N, we can have two cases:

  • Base Case: N = 0 or N = 1, then factorial(N) = 1.
  • Recurrence Relation: N > 1, then factorial(N) = N * factorial(N – 1).

Below is the implementation of the above approach:

C++
// C++ program to find factorial of given number
#include <iostream>
using namespace std;

// Function to find factorial 
// of given number
unsigned int factorial(unsigned int n)
{
    if (n == 0 || n == 1)
        return 1;
    return n * factorial(n - 1);
}

// Driver code
int main()
{
    int num = 5;
    cout << "Factorial of "
         << num << " is " << factorial(num) << endl;
    return 0;
}
C
// C program to find factorial of given number
#include <stdio.h>

// function to find factorial of given number
unsigned int factorial(unsigned int n)
{
    if (n == 0)
        return 1;
    return n * factorial(n - 1);
}

int main()
{
    int num = 5;
    printf("Factorial of %d is %d", num, factorial(num));
    return 0;
}
Java
// Java program to find factorial of given number 
class Test { 

    // Method to find factorial of the given number 
    static long factorial(int n) 
    { 
        long res = 1, i; 
        for (i = 2; i <= n; i++) 
            res *= i; 
        return res; 
    } 

    // Driver method 
    public static void main(String[] args) 
    { 
        int num = 5; 
        System.out.println( 
            "Factorial of " + num 
            + " is " + factorial(5)); 
    } 
} 
Python
# Python 3 program to find 
# factorial of given number

# Function to find factorial of given number
def factorial(n):
     
    if n == 0:
        return 1
    
    return n * factorial(n-1)

# Driver Code
num = 5;
print(f"Factorial of {num} is {factorial(num)}")
C#
// C# program to find factorial
// of given number
using System;

class Test {
    // method to find factorial
    // of given number
    static int factorial(int n)
    {
        if (n == 0)
            return 1;

        return n * factorial(n - 1);
    }

    // Driver method
    public static void Main()
    {
        int num = 5;
        Console.WriteLine("Factorial of "
                          + num + " is " + factorial(5));
    }
}
JavaScript
// Javascript to find factorial
// of given number

// function to find factorial
// of given number
function factorial(n) {
  if (n == 0) return 1;
  return n * factorial(n - 1);
}

// Driver Code
let num = 5;
console.log("Factorial of " + num + " is " + factorial(num));
PHP
<?php
// PHP program to find factorial
// of given number

// function to find factorial
// of given number
function factorial($n)
{
    if ($n == 0)
        return 1;
    return $n * factorial($n - 1);
}

    // Driver Code
    $num = 5;
    echo "Factorial of ", $num, " is ", factorial($num);

?>

Output
Factorial of 5 is 120

Time Complexity: O(n), since the function is being called n times
Auxiliary Space: O(n), In the worst case, the recursion stack space would be full with all the function calls waiting to get completed and that would make it an O(n) recursion stack space.

[Expected Approach] Using loops – O(N) Time and O(1) Space

Factorial can also be calculated iteratively as recursion can be costly for large numbers. Since the factorial of N is the product of the number itself and all its preceding numbers we can run loop i, from 1 to N. In every iteration current i, is multiplied with the product so far.

Below is the implementation for the above approach:

C++
// C++ program for factorial of a number
#include <iostream>
using namespace std;

// function to find factorial of given number
long long int factorial(int n)
{
    long long int res = 1, i;
    for (i = 1; i <= n; i++)
        res *= i;
    return res;
}

// Driver code
int main()
{
    int num = 5;
    cout << "Factorial of " << num << " is "
         << factorial(num) << endl;
    return 0;
}
C
#include <stdio.h>

// function to find factorial of given number
long long int factorial(int n)
{
    long long int res = 1, i;
    for (i = 1; i <= n; i++)
        res *= i;
    return res;
}

int main()
{
    int num = 5;
    printf(
        "Factorial of %d is %d", num, factorial(num));
    return 0;
}
Java
// Java program to find factorial of given number
class Test {

    // Method to find factorial of the given number
    static long factorial(int n)
    {
        long res = 1, i;
        for (i = 1; i <= n; i++)
            res *= i;
        return res;
    }

    // Driver method
    public static void main(String[] args)
    {
        int num = 5;
        System.out.println(
            "Factorial of " + num
            + " is " + factorial(5));
    }
}
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(1, n+1):
        res *= i
    return res

# Driver Code
num = 5;
print("Factorial of", num, "is",factorial(num))
C#
// C# program to find
// factorial of given number
using System;

class Test {
    // Method to find factorial
    // of given number
    static long factorial(int n)
    {
        long res = 1, i;

        for (i = 1; i <= n; i++)
            res *= i;
        return res;
    }

    // Driver method
    public static void Main()
    {
        int num = 5;
        Console.WriteLine(
            "Factorial of " + num
            + " is " + factorial(5));
    }
}
JavaScript
// JavaScript program to find factorial of given number

// Method to find factorial of the given number
function factorial(n)
{
    var res = 1, i;
    for (i = 1; i <= n; i++)
        res *= i;
    return res;
}

// Driver method

var num = 5;
console.log("Factorial of " + num + " is "
               + factorial(5));
PHP
<?php
// function to find factorial of given number
function factorial($n)
{
    $res = 1;
    for ($i = 1; $i <= $n; $i++) {
        $res *= $i;
    }
    return $res;
}

// Driver code
$num = 5;
echo "Factorial of $num is " . factorial($num) . "\n";
?>

Output
Factorial of 5 is 120

Time Complexity: O(n), since we are running a loop from 1 to n.
Auxiliary Space: O(1)


The above solution cause overflow for large numbers. Please refer factorial of large number for a solution that works for large numbers.
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.



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
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
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
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
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
Check if a subarray of length K with sum equal to factorial of a number exists or not
Given an array arr[] of N integers and an integer K, the task is to find a subarray of length K with a sum of elements equal to factorial of any number. If no such subarray exists, print “-1”. Examples: Input: arr[] = {23, 45, 2, 4, 6, 9, 3, 32}, K = 5Output: 2 4 6 9 3Explanation:Subarray {2, 4, 6, 9, 3} with sum 24 (= 4!) satisfies the required co
12 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
Count of integer whose factorial of digit sum contains every digit of original number
Given an array arr[] of length n which contains positive integers (0 ≤ arr[i] ≤ 109), the task is to count the number of elements present in the given array such that the factorial of their digit sum (we will do digit sum while its value is greater than 10) contains every digit present in the original integer. Examples: Input: arr[] = [653, 663, 24
14 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 minimum number X such that sum of factorial of its digits is N
Given a number N, the task is to find the minimum number X such that A(X) = N, where A(X) for positive integer X is the sum of factorials of its digits. For example, A(154) = 1! + 5! + 4!= 145. Return a list of digits which represent the number X. Example: Input: N = 40321Output: 18Explanation: A(18) =1! + 8! = 40321. Note that A(80) and A(81) are
6 min read
Find minimum number K such that its factorial is multiple of N
Given an integer N. The task is to find minimum K such that the factorial of K is multiple of N. (2 &#x2264 N &#x2264 1012) Examples: Input: N = 30Output: 5Explanation: 5! % 30 = 120 % 30 = 0, Therefore 5 is the answer Input: N = 280Output: 7 Approach: To solve the problem follow the below idea: Binary Search can be used to solve this problem. Numb
14 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
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
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
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
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
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
Factorial of each element in Fibonacci series
Given the upper limit, print factorials of all Fibonacci Numbers smaller than the limit.Examples : Input : limit = 20 Output : 1 1 1 2 6 120 40320 6227020800 Explanation : Fibonacci series in this range is 0, 1, 1, 2, 3, 5, 8, 13. Factorials of these numbers are output. Input : 50 Output : 1 1 1 2 6 120 40320 6227020800 51090942171709440000 2952327
11 min read
Expressing factorial n as sum of consecutive numbers
Given two numbers N and M. Find the number of ways in which factorial N can be expressed as a sum of two or more consecutive numbers. Print the result modulo M.Examples: Input : N = 3, M = 7 Output : 1 Explanation: 3! can be expressed in one way, i.e. 1 + 2 + 3 = 6. Hence 1 % 7 = 1 Input : N = 4, M = 7 Output : 1 Explanation: 4! can be expressed in
13 min read
Range and Update Sum Queries with Factorial
Given an array arr[] of N integers and number of queries Q. The task is to answer three types of queries. Update [l, r] – for every i in range [l, r] increment arr[i] by 1.Update [l, val] – change the value of arr[l] to val.Query [l, r] – calculate the sum of arr[i]! % 109 for all i in range [l, r] where arr[i]! is the factorial of arr[i]. Prerequi
15+ min read
Check if N is a Factorial Prime
Given a positive integer N, the task is to check if N is a Factorial prime or not. If it is a factorial prime then print YES else print NO.Note: In mathematics, a factorial prime number is a prime number that is one less than or one more than a factorial of any number. First few factorial primes are 2, 3, 5, 7, 23, 719, 5039, ....Examples: Input: N
9 min read