Getting big random numbers in C/C++

ForceBru picture ForceBru · Jan 23, 2015 · Viewed 17.2k times · Source

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!!

Answer

Baum mit Augen picture Baum mit Augen · Jan 23, 2015

You can easily do this with std::uniform_int_distribution<unsigned long long>.

Simple example code (taken from here, modified to use unsigned long long):

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<unsigned long long> dis(lowerBorder, upperBorder);

    for (int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

Note that the seeding of the mersenne twister as done here for demo purposes is not perfect, for example see here.