在 C/C++ 中获取大随机数
标准 rand()
函数给出的数字对我来说不够大:我需要 unsigned long long
的.我们如何获得真正大的随机数?我尝试修改一个简单的散列函数,但它太大大,运行时间太长,而且永远不会产生小于 1e5 的数字!!
Standard rand()
function gives numbers not big enough for me: I need unsigned long long
ones. How do we get really big random numbers? I tried modifying a simple hash function but it's too big, takes too long to run and never produces numbers which are less than 1e5!!
推荐答案
这是一个返回随机 64 位数字的便携式 C99 解决方案:
Here's a portable C99 solution that returns a random 64-bit number:
unsigned long long llrand() {
unsigned long long r = 0;
for (int i = 0; i < 5; ++i) {
r = (r << 15) | (rand() & 0x7FFF);
}
return r & 0xFFFFFFFFFFFFFFFFULL;
}
说明:rand()
返回 0 到 RAND_MAX
范围内的整数,并且 RAND_MAX
只保证至少为 32,767(15 个随机位).long long
保证有 64 位,但可能更大.
Explanation: rand()
returns integers in the range 0 to RAND_MAX
and RAND_MAX
is only guaranteed to be at least 32,767 (15 random bits). long long
is guaranteed to have 64 bits but may be larger.
相关文章