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

£可爱£侵袭症+ 提交于 2019-12-12 21:19:04

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/13583169/how-to-work-out-how-many-bits-the-result-of-a-factorial-should-take-up-as-a-numb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!