Search code examples
factorial

How to work out how many bits the result of a factorial should take up as a number?


The factorial function could return a very large number as a result.

How could I work out the size of the data which must return as a result of the factorial? Is there a function which can give me the size of the data quickly based upon the number n for which we are computing the factorial?

For example, factorial (5) = 5 * 4 * 3 * 2 = 120

The number 120 will be 120 = 0b1111000 where 0b indicates this is a binary number. At least, I need 7 bits to represent the result and probability I would like to fit that into 8 bits to be a byte.


Solution

  • you need to calculate log2(factorial(N)), rounded up to the next higher number to get the number of bits you need to represent the result. if you're not sure if your can calculate or represent the factorial result with your current setup, you may try to calculate the sum of log2(i) for all i in the range from 2 to N inclusive (including 2 and N, that is).

    as a sample, let's calculate the number of bits for factorial(5):

    log2(120) = 6.906, rounded up become 7 (bits)
    

    otheriwise,

    log2(2) + log2(3) + log2(4) + log2(5) = 6.906, which gives same result