Program for factorial of a number - GeeksforGeeks

14 Mar, 2022
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. 
Recursive Solution: Factorial can be calculated using following recursive formula.  
  n! = n * (n-1)!
  n! = 1 if n = 0 or n = 1
 
Following is implementation of factorial.  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find factorial of given number#include <iostream>using namespace std; // function to find factorial of given numberunsigned int factorial(unsigned int n){    if (n == 0)        return 1;    return n * factorial(n - 1);} // Driver codeint main(){    int num = 5;    cout << "Factorial of "         << num << " is " << factorial(num) << endl;    return 0;} // This code is contributed by Shivi_Aggarwal
// C program to find factorial of given number#include <stdio.h> // function to find factorial of given numberunsigned 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 program to find factorial of given numberclass 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));    }}
# Python 3 program to find# factorial of given number # Function to find factorial of given numberdef factorial(n):          if n == 0:        return 1         return n * factorial(n-1)  # Driver Codenum = 5;print("Factorial of", num, "is",factorial(num))  # This code is contributed by Smitha Dinesh Semwal
// C# program to find factorial// of given numberusing 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 program to find factorial// of given number // function to find factorial// of given numberfunction 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?>
<script>// Javascript to find factorial// of given number // function to find factorial// of given numberfunction factorial(n) {  if (n == 0) return 1;  return n * factorial(n - 1);} // Driver Codelet num = 5;document.write("Factorial of " + num + " is " + factorial(num)); // This code is contributed by Saurabh Jaiswal </script>
Output: 
Factorial of 5 is 120
Iterative Solution: 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 loop. Using For loop  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for factorial of a number#include <iostream>using namespace std; // function to find factorial of given numberunsigned int factorial(unsigned int n){    int res = 1, i;    for (i = 2; i <= n; i++)        res *= i;    return res;} // Driver codeint main(){    int num = 5;    cout << "Factorial of "         << num << " is "         << factorial(num) << endl;    return 0;} // This code is contributed by Shivi_Aggarwal
#include <stdio.h> // function to find factorial of given numberunsigned 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 program to find factorial of given numberclass 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));    }}
# Python 3 program to find# factorial of given number # Function to find factorial of given numberdef factorial(n):          res = 1         for i in range(2, n+1):        res *= i    return res # Driver Codenum = 5;print("Factorial of", num, "is",factorial(num))  # This code is contributed by Smitha Dinesh Semwal
// C# program to find// factorial of given numberusing 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 // function to find factorial// of given numberfunction 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.?>
<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
Using While loop  
C
C++
Java
Python3
C#
Javascript
// C program for factorial of a number#include <stdio.h> // function to find factorial of given numberunsigned 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++ program for factorial of a number#include <iostream>using namespace std; // function to find factorial of given// number using while loopunsigned 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 codeint main(){    int num = 5;    cout << "Factorial of "         << num << " is "         << factorial(num) << endl;    return 0;}// This code is contributed by Shivi_Aggarwal
// 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));    }}
# Python 3 program to find# factorial of given number # Function to find factorial of given numberdef factorial(n):    if(n == 0):       return 1    i = n    fact = 1         while(n / i != n):        fact = fact * i        i -= 1             return fact # Driver Codenum = 5;print("Factorial of", num, "is",factorial(num))  # This code is contributed by Smitha Dinesh Semwal
// C# program to find// factorial of given numberusing 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));    }}
<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 of the above iterative solutions is O(n).One line Solution (Using Ternary operator):  
C++
C
Java
Python3
C#
PHP
Javascript
// 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 Codeint main(){    int num = 5;    cout << "Factorial of " << num << " is "<< factorial(num);    return 0;} // This code is contributed by shivanisinghss2110
// 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 Codeint main(){    int num = 5;    printf("Factorial of %d is %d", num, factorial(num));    return 0;} // This code is contributed by  Rithika palaniswamy.
// Java program to find factorial// of given numberclass 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.
# 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 Codenum = 5print ("Factorial of", num, "is",      factorial(num)) # This code is contributed# by Smitha Dinesh Semwal.
// C# program to find factorial// of the given numberusing 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 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.?>
<script> // JavaScript program to find factorial of given numberfunction 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
YouTubeGeeksforGeeks506K subscribersC Program for factorial of a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=T9_ojJJeVSc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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. 
jit_t
vt_m
Shivi_Aggarwal
aspiring_codeking
nikhilaggarwal3
shrey_shreyansh
reapedjuggler
_saurabh_jaiswal
lokeshpotta20
shivanisinghss2110
adeebkmd
factorial
Inautix
MAQ Software
Morgan Stanley
Samsung
Wipro
Mathematical
School Programming
Morgan Stanley
Samsung
MAQ Software
Wipro
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects