如何计算阶乘结果应占用多少位? [英] How to work out how many bits the result of a factorial should take up as a number?

查看:115
本文介绍了如何计算阶乘结果应占用多少位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阶乘函数可能会返回非常大的数字.

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

我如何计算因式分解结果必须返回的数据大小?是否有一个函数可以根据我们要计算阶乘的数字n迅速给我数据的大小?

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?

例如,阶乘(5)= 5 * 4 * 3 * 2 = 120

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

数字120将为120 = 0b1111000,其中0b表示这是一个二进制数.至少我需要7位来表示结果,并希望将其适合8位作为一个字节的概率.

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.

推荐答案

您需要计算log2(factorial(N)),四舍五入到下一个更高的数字,以获得表示结果所需的位数.如果不确定当前的设置是否可以计算或表示阶乘结果,则可以尝试计算所有ilog2(i)之和,范围为2到N(包括2和N,是).

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).

作为示例,让我们计算factorial(5)的位数:

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

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

否则,

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

这篇关于如何计算阶乘结果应占用多少位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆