Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ program to calculate quotients of large factorials

Tags:

c++

How can I write a c++ program to calculate large factorials.

Example, if I want to calculate (100!) / (99!), we know the answer is 100, but if i calculate the factorials of the numerator and denominator individually, both the numbers are gigantically large.

like image 399
xbonez Avatar asked Apr 28 '10 16:04

xbonez


People also ask

How do you find the factorial of 100 in C?

How to calculate 100 factorial (100!) in C. 0916864000000000000000000000000 which is 158 digits long and the maximum value of unsigned long long int in C is 18,446,744,073,709,551,615.


1 Answers

expanding on Dirk's answer (which imo is the correct one):

#include "math.h"
#include "stdio.h"
int main(){
  printf("%lf\n", (100.0/99.0) * exp(lgamma(100)-lgamma(99)) );
}

try it, it really does what you want even though it looks a little crazy if you are not familiar with it. Using a bigint library is going to be wildly inefficient. Taking exps of logs of gammas is super fast. This runs instantly.

The reason you need to multiply by 100/99 is that gamma is equivalent to n-1! not n!. So yeah, you could just do exp(lgamma(101)-lgamma(100)) instead. Also, gamma is defined for more than just integers.

like image 56
frankc Avatar answered Oct 07 '22 23:10

frankc