Is There Any Built-in Factorial Function in 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++? 6 6 Answers Although...
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++ ?
6 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));
}
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.
No, there is no such function in the Standard Library.
No, in standard c++ , there is no such function as factorial ,But you can find same functionality in boost library : boost::math::factorial
STL doesn't provide function for Factorial but you can calculate in one line recursively:
int fact(int n){
return (n==0) || (n==1) ? 1 : n* fact(n-1);
}
As mentioned previously, there is no such a function in the standard library. Since recursive definitions may be not optimal in the terms of execution speed, I would recommend the iterative aproach:
long factorial(const int n)
{
long f = 1;
for (int i=1; i<=n; ++i)
f *= i;
return f;
}
Writing a slow version of factorial even with DP in C or C++ is easy. However, there is a much faster algorithm implemented in Python 3:
See
So, it would be good to add it to the STL imho.