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

Program for factorial of a number

Last Updated : 12 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

What is the factorial of a number?

  • Factorial of a non-negative integer is the multiplication of all positive integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. 
  • A factorial is represented by a number and a  ” ! ”  mark at the end. It is widely used in permutations and combinations to calculate the total possible outcomes. A French mathematician Christian Kramp firstly used the exclamation.
     

Recommended Practice

Let’s create a factorial program using recursive functions. Until the value is not equal to zero, the recursive function will call itself. Factorial can be calculated using the following recursive formula. 
 

n! = n * (n – 1)!
n! = 1 if n = 0 or n = 1

Below is the implementation: 

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;
}
// This code is contributed by Shivi_Aggarwal


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


Python3




# 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("Factorial of", num, "is",
factorial(num))
   
# This code is contributed by Smitha Dinesh Semwal


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));
    }
}
  
// This code is contributed by vt_m


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);
  
// This code is contributed by m_kit
?>


Javascript




<script>
// 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;
document.write("Factorial of " + num + " is " + factorial(num));
  
// This code is contributed by Saurabh Jaiswal
  
</script>


Output

Factorial of 5 is 120

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

Iterative Solution to find factorial of a number:

Factorial can also be calculated iteratively as recursion can be costly for large numbers. Here we have shown the iterative approach using both for and while loops. 

Approach 1: Using For loop 

Follow the steps to solve the problem:

  • Using a for loop, we will write a program for finding the factorial of a number. 
  • An integer variable with a value of 1 will be used in the program. 
  • With each iteration, the value will increase by 1 until it equals the value entered by the user. 
  • The factorial of the number entered by the user will be the final value in the fact variable.

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
unsigned int factorial(unsigned int n)
{
    int res = 1, i;
    for (i = 2; i <= n; i++)
        res *= i;
    return res;
}
  
// Driver code
int main()
{
    int num = 5;
    cout << "Factorial of "
         << num << " is "
         << factorial(num) << endl;
    return 0;
}
  
// This code is contributed by Shivi_Aggarwal


C




#include <stdio.h>
  
// function to find factorial of given number
unsigned int factorial(unsigned int n)
{
    int res = 1, i;
    for (i = 2; 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 int factorial(int n)
    {
        int 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));
    }
}


Python3




# 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))
   
# This code is contributed by Smitha Dinesh Semwal


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)
    {
        int res = 1, i;
  
        for (i = 2; i <= n; i++)
            res *= i;
        return res;
    }
  
    // Driver method
    public static void Main()
    {
        int num = 5;
        Console.WriteLine(
            "Factorial of " + num
            + " is " + factorial(5));
    }
}
  
// This code is contributed by vt_m


PHP




<?php
  
// function to find factorial 
// of given number
function factorial( $n)
{
    $res = 1; $i;
    for ($i = 2; $i <= $n; $i++)
        $res *= $i;
    return $res;
}
  
// Driver Code
$num = 5;
echo "Factorial of ", $num, " is ", 
                    factorial($num);
  
// This code is contributed 
// by anuj_67.
?>


Javascript




<script>
// 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 = 2; i <= n; i++)
            res *= i;
        return res;
    }
  
    // Driver method
      
        var num = 5;
        document.write("Factorial of " + num + " is " + factorial(5));
  
  
// This code is contributed by shivanisinghss2110.
  
</script>


Output

Factorial of 5 is 120

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

Approach 2: This example uses a while loop to implement the algorithm and find the factorial program.

C




// C program for factorial of a number
#include <stdio.h>
  
// function to find factorial of given number
unsigned int factorial(unsigned int n)
{
     if(n == 0)
          return 1;
    int i = n, fact = 1;
    while (n / i != n) {
        fact = fact * i;
        i--;
    }
    return fact;
}
  
int main()
{
    int num = 5;
    printf("Factorial of %d is %d", num, factorial(num));
    return 0;
}


C++




// C++ program for factorial of a number
#include <iostream>
using namespace std;
  
// function to find factorial of given
// number using while loop
unsigned int factorial(unsigned int n)
{
    if(n == 0)
          return 1;
    int i = n, fact = 1;
    while (n / i != n) {
        fact = fact * i;
        i--;
    }
    return fact;
}
  
// Driver code
int main()
{
    int num = 5;
    cout << "Factorial of "
         << num << " is "
         << factorial(num) << endl;
    return 0;
}
// This code is contributed by Shivi_Aggarwal


Java




// Java program to find factorial of given number
  
class Test {
  
    // Method to find factorial of the given number
    static int factorial(int n)
    {
        if(n == 0)
           return 1;
        int i = n, fact = 1;
        while (n / i != n) {
            fact = fact * i;
            i--;
        }
        return fact;
    }
  
    // Driver method
    public static void main(String[] args)
    {
        int num = 5;
        System.out.println(
            "Factorial of " + num
            + " is " + factorial(5));
    }
}


Python3




# Python 3 program to find 
# factorial of given number
  
# Function to find factorial of given number
def factorial(n):
    if(n == 0):
       return 1
    i = n
    fact = 1
      
    while(n / i != n):
        fact = fact * i
        i -= 1
          
    return fact
  
# Driver Code
num = 5;
print("Factorial of", num, "is",
factorial(num))
   
# This code is contributed by Smitha Dinesh Semwal


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;
        int i = n, fact = 1;
        while (n / i != n) {
            fact = fact * i;
            i--;
        }
        return fact;
    }
  
    // Driver method
    public static void Main()
    {
        int num = 5;
        Console.WriteLine(
            "Factorial of " + num
            + " is " + factorial(5));
    }
}


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
        // function to find factorial of given
        // number using while loop
        function factorial(n) {
            if (n == 0)
                return 1;
            let i = n, fact = 1;
            while (Math.floor(n / i) != n) {
                fact = fact * i;
                i--;
            }
            return fact;
        }
  
        // Driver code
        let num = 5;
        document.write("Factorial of "
            + num + " is "
            + factorial(num) + "<br>");
  
// This code is contributed by Potta Lokesh
  
    </script>


Output

Factorial of 5 is 120

Time complexity: O(N)
Auxiliary Space: O(1)

Approach 3: A ternary operator can be thought of as a shorthand for an if…else statement. The conditions are provided, along with statements to be executed based on them. Here’s the program for factorial using a ternary operator.

C++




// C++ program to find factorial of given number
#include <iostream>
using namespace std;
  
int factorial(int n)
{
    // single line to find factorial
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
  
// Driver Code
int main()
{
    int num = 5;
    cout << "Factorial of " << num << " is "<< factorial(num);
    return 0;
}
  
// This code is contributed by shivanisinghss2110


C




// C++ program to find factorial of given number
#include <stdio.h>
  
int factorial(int n)
{
    // single line to find factorial
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
  
// Driver Code
int main()
{
    int num = 5;
    printf("Factorial of %d is %d", num, factorial(num));
    return 0;
}
  
// This code is contributed by  Rithika palaniswamy.


Java




// Java program to find factorial
// of given number
class Factorial {
  
    int factorial(int n)
    {
  
        // single line to find factorial
        return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
    }
  
    // Driver Code
    public static void main(String args[])
    {
        Factorial obj = new Factorial();
        int num = 5;
        System.out.println(
            "Factorial of " + num
            + " is " + obj.factorial(num));
    }
}
  
// This code is contributed by Anshika Goyal.


Python3




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


C#




// C# program to find factorial
// of the given number
using System;
  
class Factorial {
  
    int factorial(int n)
    {
  
        // single line to find factorial
        return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
    }
  
    // Driver Code
    public static void Main()
    {
        Factorial obj = new Factorial();
        int num = 5;
  
        Console.WriteLine(
            "Factorial of " + num
            + " is " + obj.factorial(num));
    }
}
  
// This code is contributed by vt_m.


PHP




<?php
// PHP program to find factorial
// of given number
  
function factorial( $n)
{
      
    // single line to find factorial
    return ($n == 1 || $n == 0) ? 1: 
             $n * factorial($n - 1); 
}
  
    // Driver Code
    $num = 5;
    echo "Factorial of ", $num, " is ", factorial($num);
  
// This code is contributed by anuj_67.
?>


Javascript




<script>
  
// JavaScript program to find factorial of given number
function factorial(n)
{
    // single line to find factorial
    return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
  
// Driver Code
  
    var num = 5;
    document.write("Factorial of " +num +" is " + factorial(num));
  
// This code is contributed by shivanisinghss2110.
  
</script>


Output

Factorial of 5 is 120

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

Problems in writing code of factorial

When the value of n changes increases by 1, the value of the factorial increases by n. So the variable storing the value of factorial should have a large size. Following is the value of n whose factorial can be stored in the respective size.

1. integer –> n<=12

2. long long int –> n<=19

From the above data, we can see that a very small value of n can be calculated because of the faster growth of the factorial function. We can however find the mod value of factorial of larger values by taking mod at each step.

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 : 2 Recommended PracticeFind the last d
10 min read
Java Program for factorial of a number
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. In this article, we will learn how to write a program for the factorial of a number in Java. Formulae for Factorialn! = n * (n-1) * (n-2) * (n-3) * ........ * 1 Example of Factorial in Java 6! == 6*5*4*3*2*1 = 720. 5! == 5*4*3*2*1 = 1204! == 4*3*2*1 =
3 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
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
C++ Program to Find Factorial of a Number Using Iteration
Factorial of a number n is the product of all integers from 1 to n. In this article, we will learn how to find the factorial of a number using iteration in C++. Example Input: 5Output: Factorial of 5 is 120Factorial of Number Using Iteration in C++To find the factorial of a given number we can use loops. First, initialize the factorial variable to
2 min read
C++ Program to Find Factorial of a Number Using Dynamic Programming
The Factorial of a number N can be defined as the product of numbers from 1 to the number N. More formally factorial of n can be defined by function, [Tex]f(n) = 1 \times 2 \times 3 \times... \ n[/Tex] In this article, we will learn how to find the factorial of a number using dynamic programming in C++. Example: Input: n = 5 Output: Factorial = 120
2 min read
Python Program to Find the Factorial of a Number
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 approachThis Python program uses a recursive function to calculate the factorial of a given number. The factorial is computed by multiplying the num
4 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 xExamples: Input: N = 24Output: YesExplanation: 4! = 24 Input: N = 25Output: No Recommended PracticeFactorial NumberTry It!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
4 min read
Factorial Program in C
A factorial is the product of all the natural numbers less than or equal to the given number n. For Example, the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. In this article, we will explore a few programs to find the factorial of a number in C. We can write the factorial program in C using two methods: Using LoopsUsing Recursion1. Factori
2 min read
three90RightbarBannerImg