C++11 random numbers

This is how to use the C++11 random number generation for this purpose (adjusted from http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution):

#include <random>
#include <iostream>
int main()
{
  /* Initialise. Do this once (not for every
     random number). */
  std::random_device rd;
  std::mt19937_64 gen(rd());

  /* This is where you define the number generator for unsigned long long: */
  std::uniform_int_distribution<unsigned long long> dis;

  /* A few random numbers: */    
  for (int n=0; n<10; ++n)
    std::cout << dis(gen) << ' ';
  std::cout << std::endl;
  return 0;
}

Instead of unsigned long long, you could use std::uintmax_t from cstdint to get the largest possible integer range (without using an actual big-integer library).

Leave a Comment