I am trying to find the numbers till 100!
(factorial) but after 20!
it gives an error as the value is too large to handle. How can I store such a
How would you do it on paper?
Doing multiplications with numbers 160-digits long is not that hard for a computer.
Try writing your own function or use an existing library.
This code will help up to 170!
. Use double for the factorial function, because normal int or long int will not support that factorial result, double will support up to 1.7e308
.
#include<stdio.h>
double fact(int k){
int i;
double f=1;
for(i=1;i<=k;i++) f=f*i;
return (f);
}
int main(){
int i;
for(i=1;i<=65;i++)
printf("%d! = %.3lf\n",i,fact(i));
return 0;
}
20 factorial is 19 digits long. 100 factorial is 158 digits long, taking up 500 bits! It's actually:
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000
00000000
None of the standard types will work for you here, what you'll have to do is implement your own routine for handling such large numbers.
For example you will need to accept that multiplying two 32 bit values together may result in a 64 bit result.
This was coommon practice for calculating large numbers in the days of 8 bit processors. Its referred to as arbitrary precision arithemtic.
Here's a link to describe how this was done. Admittedly it's for assembler, but it still holds true here. You'll need to take into account the default sizes of int
on your system.
At least on Linux, a possible multi-precision library could be GMP (it also works on Solaris, Windows, MacOSX, etc...).