C++ Program to Find Factorial

In the previous article, we have discussed about C++ Program to Display Fibonacci Series. Let us learn how to find factorial in C++ Program.

Methods to find factorial of a given number in c++

In this article, we discuss different methods of how we can find the factorial of a given number in c++. The list of methods that we will discuss is given below.

Before discussing the different methods let first understand what a factorial of the given number is. 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.

Now we will discuss different methods to find the factorial of a given number.
<h3>Method 1-Iterative approach

As we discussed above that the factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. Hence we simply apply a for loop from 1 to a given number a store their multiplication in a variable and then print it. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    int res = 1, i,n=6;
    for (i = 1; i <= n; i++)
    {
        res *= i;
    }
    cout<<"Factorial of given number "<<n<<" is "<<res;
    
    return 0;
}

Output

Factorial of given number 6 is 720

Method 2-Using Recursion

Let analyze how we can calculate the factorial of a given number using recursion.

Suppose we want to calculate the factorial of the number 6. So we can write it as:-

factorial(6)=6*5*4*3*2*1  and if we analyze that 5*4*3*2*1 is also the factorial of number 5 so we can break factorial of 6 into factorial(6)=6* factorial(5) So that’s how we can call the recursive function. Let write the code for this.

#include <iostream>
using namespace std;
int factorial(unsigned int n)
{
    if (n == 0)
        return 1;
    return n * factorial(n - 1);
}
int main() {
    int n=6;
    cout<<"Factorial of given number "<<n<<" is "<<factorial(6);
    
    return 0;
}

Output

Factorial of given number 6 is 720

Method 3-Using Dynamic Programming

The problem with the above recursive is that we have to call the recursive function for a particular number multiple times. Here Dynamic programming solves this problem. Instead of calling a recursive function for a given number again and again we store the result of that number in an array and when this number we directly return its value from the array instead of calculating the value again. Let’s write the code for this.

#include <iostream>
using namespace std;
int result[1000] = {0};
int factorial(int n) {
   if (n >= 0) {
      result[0] = 1;
      for (int i = 1; i <= n; ++i) {
         result[i] = i * result[i - 1];
      }
      return result[n];
   }
}
int main() {
   int n=6;
   cout<<"Factorial of a given number "<<n<<" is "<<factorial(n);
   return 0;
}

Output

Factorial of a given number 6 is 720

So these are the methods to calculate the factorial of a given number in c++.