Find factorial using tgamma in C++

In this tutorial, we are going to discuss how to calculate the factorial of a number using an inbuilt function tgamma. Let’s first discuss the factorial of numbers with examples and then about tgamma function.

We can calculate the factorial of a number(a non-negative number or a whole number) by calculating the product of all the positive numbers less than or equal to that number.

Factorial(n) = n.(n-1).(n-2).. 1

(or)

n! = n.(n-1).(n-2).. 1

Example : 

5! = 5.4.3.2.1 = 120

10! = 10.9.8.7.6.5.4.3.2.1 = 3628800

Note : Factorial(0) = 1

In C++, we can calculate the factorial of a number in multiple ways like using loops, recursive calls, tgamma function. Now let’s discuss what is tgamma function in C++, then we will look into a small example code to understand it clearly.

Using tgamma function to calculate factorial of a number in C++

Generally in mathematics gamma function is used to find the factorial of numbers, for every positive number n

tgamma(n) = (n-1)!

C++ standard library cmath provides us tgamma() function which takes a natural number as an argument. Initially in our code, we have to include cmath header file in order to use tgamma function to find the factorial of a positive number n.

tgamma() function in C++, takes a number of type float, double, and long double as arguments and returns the factorial of that number minus one as output which is of the same data type. If the argument is zero or negative numbers it will show domain errors.

Code :

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    
    long double num = 6;
    long double factorial = tgamma(num + 1);
    cout<< "Factorial of " << num << " is : " << factorial << "\n";
    return 0;
}

Output : 

Factorial of 6 is : 720

In tgamma(parameter) function call we have mentioned num+1, because tgamma function is used to calculate factorial by considering a number 1 less than the number we have passed as an argument. If we have used the num of int type and pass 6 as an argument it will return 719 instead of 720 because of type conversions while returning the factorial value.

Hope you have understood the entire discussion.

Also read: Factorial of Large Number Using boost multiprecision in C++

Leave a Reply

Your email address will not be published. Required fields are marked *