问题描述
标准兰特()
函数提供的数字不够大对我来说:我需要无符号长长
的。我们怎样才能达到真正的大的随机数?我试图改变一个简单的哈希函数,但它太的大的,需要很长时间才能运行,从来没有产生这是小于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;
}
说明:兰特()
返回范围0-2的整数 RAND_MAX
和 RAND_MAX
只能保证至少有32,767(15个随机位)。 长长
都保证有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.
这篇关于渐大的随机数在C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!