1到40亿求和需要多少存储空间
受到这个问题的启发(找到一个不在四十亿给定整数之中的整数)。
存储一个 1 到 40 亿数字之和的整数需要多少存储空间?
例如,1+2+3+4+5 = 15。1 到 100 万的总和 = 500,000,500,000。
这里是一个可能有帮助的算法
Inspired by this question (Find an integer not among four billion given ones).
How much storage space would it require to store an integer that was the summation of the numbers 1 to 4 billion?
For example, 1+2+3+4+5 = 15. Summation of 1 to 1 million = 500,000,500,000.
Here is an algorithm that may help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您链接的函数描述如何查找第 n 个Triangle Number ,定义为从 1 到 n 的 n 个自然数之和。
将 40 亿作为 n 代入函数,得到 8000000002000000000。
将其表示为位数,可以通过取该值的以 2 为底的对数并向上舍入来计算出 -
ceil(log(8000000002000000000)/log(2)) = 63
因此,需要 63 位存储空间。
The function you link to describe how to find the n'th Triangular Number, which is defined as the sum of the n natural numbers from 1 to n.
Substituting 4 billion as n into the function gives 8000000002000000000.
Expressing that as a number of bits can be worked out by taking the base-2 logarithm of the value and rounding up -
ceil(log(8000000002000000000)/log(2)) = 63
So, 63 bits of storage are required.
答案:63 位。
Answer: 63 bits.
如果您为整数选择适当的编码,一位就足够了。
如果您可能需要存储超过 2^n 个可能的值,则只需要超过 n 位。这里您只需要能够存储一个值。
One bit is plenty, if you choose an appropriate encoding for integers.
You only need more than n bits if there are more than 2^n possible values you could potentially need to store. Here there is only one value that you require to be able to store.