Higher Factorials
Published:
Factorial :
Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n.
n! = n * (n-1) * (n-2) * ....... * 1
For normal n values upto 15 we can get the factorials by the above formula however, for higher values the product will be get rising upto big integers so the above formula will be failed in the computers to solve.
To solve higher factorials we have two approaches:
Stirling approximation:
is an approximation for calculating factorials. It is also useful for approximating the log of a factorial.
n! =~ sqrt(2*pi*n) * pow((n/e), n)
Note:
This formula will not give the exact value of the factorial because it is just the approximation of the factorial.
Code :
long long int stirlingApproximation(int n){
if (n == 1)
return 1;
long long int z;
float e = 2.71;
z = sqrt(2*3.14*n) * pow((n/e), n);
return z;
}
Similary we have,
Ramanujan's Factorial approximation:
is an approximation for calculating factorials. It is also useful for approximating the log of a factorial.
The approximation of Ramanujan is :
Implementation 1 :
def ramanujan(x):
fact = sqrt(pi)*(x/e)**x
fact *= (((8*x + 4)*x + 1)*x + 1/30.)**(1./6.)
return fact
Implementation 2 (trickier implementation):
def ramanujan2(x):
fact = sqrt(pi)*(x/e)**x
fact *= (((8*x + 4)*x + 1)*x + 1/30.)**(1./6.)
if isinstance(x, int):
fact = int(fact)
return fact