我正在实现通用哈希并使用以下通用哈希函数:
h(k)=((A*k)mod 2^64) rsh 64-r
其中A是介于
之间的随机数2^61 and 2^62.
C++ 中的 rand()
函数具有返回类型 integer 并且它不能生成那么大的数字。那么我怎样才能生成这个范围内的随机数呢? (数字应该是非常随机的,即每个数字应该有相同的概率被选中)
注意:
long long int random=rand();
不起作用,因为 rand
返回的数字是 int。
最佳答案
在 C++11 中,您可以使用 random header和 std::uniform_int_distribution连同 64-bit instance of std::mersenne_twister_engine这应该可以满足您的需求 ( see it live ):
#include <iostream>
#include <random>
#include <cmath>
int main()
{
std::random_device rd;
std::mt19937_64 e2(rd());
std::uniform_int_distribution<long long int> dist(std::llround(std::pow(2,61)), std::llround(std::pow(2,62)));
std::cout << std::llround(std::pow(2,61)) << std::endl;
std::cout << std::llround(std::pow(2,62)) << std::endl;
for (int n = 0; n < 10; ++n) {
std::cout << dist(e2)<< ", " ;
}
std::cout << std::endl ;
}
如果 C++11 不是一个选项,那么似乎有源代码可用于 several 64-bit Mersenne Twister implementations .
关于c++ - 如何生成64位随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096015/