Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a number greater than 20! (factorial)

Tags:

c

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 number?

like image 568
Rishabh Avatar asked Nov 15 '11 09:11

Rishabh


2 Answers

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.

like image 86
ChrisBD Avatar answered Nov 15 '22 23:11

ChrisBD


At least on Linux, a possible multi-precision library could be GMP (it also works on Solaris, Windows, MacOSX, etc...).

like image 31
Basile Starynkevitch Avatar answered Nov 15 '22 23:11

Basile Starynkevitch