Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any built-in factorial function in c++?

Tags:

c++

I have searched but I was not able to find this. Would anyone please tell me that if there is any built-in factorial function in c++ ?

like image 693
Sohel Avatar asked May 02 '18 10:05

Sohel


People also ask

Is there any function for factorial?

The factorial function is defined for all positive integers, along with 0. What value should 0! have? It's the product of all integers greater than or equal to 1 and less than or equal to 0. But there are no such integers.

Does factorial exist in math module?

factorial() function. In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math. factorial() function returns the factorial of desired number.

Is recursion a factorial?

A recursive function is a nonleaf function that calls itself. The factorial function can be written as a recursive function call.


2 Answers

Although there is no C function defined specifically for computing factorials, C math library lets you compute gamma function. Since Г(n) = (n-1)! for positive integers, using tgamma of i+1 yields i!.

If you use a user-defined factorial function, this would print identical numbers:

for (int i = 1 ; i != 10 ; i++) {
    printf("%lld %f\n", factorial(i), tgamma(i+1));
}

Demo.

1 1.000000
2 2.000000
6 6.000000
24 24.000000
120 120.000000
720 720.000000
5040 5040.000000
40320 40320.000000
362880 362880.000000

Note: Considering how easy it is to code up factorial function, using gamma to compute factorials is a lot like killing a fly with a sledgehammer.

like image 185
Sergey Kalinichenko Avatar answered Oct 12 '22 18:10

Sergey Kalinichenko


No, there is no such function in the Standard Library.

like image 6
Vittorio Romeo Avatar answered Oct 12 '22 18:10

Vittorio Romeo