How to generate very Large random number in c++

With c++11, using the standard random library of c++11, you can do this:

#include <iostream>
#include <random>

int main()
{
  /* Seed */
  std::random_device rd;

  /* Random number generator */
  std::default_random_engine generator(rd());

  /* Distribution on which to apply the generator */
  std::uniform_int_distribution<long long unsigned> distribution(0,0xFFFFFFFFFFFFFFFF);

  for (int i = 0; i < 10; i++) {
      std::cout << distribution(generator) << std::endl;
  }

  return 0;
}

Live Demo


As a uniformly random number in the range [0, 2^64) is just 64 random bits, you can just use the return values of std::mt19937_64 directly:

#include <random>

int main () {
    std::mt19937_64 gen (std::random_device{}());

    std::uint64_t randomNumber = gen();
}

Note that seeding a Mersenne Twister engine with a single 32 bit seed is not optimal, for a better way, have a look at this.

Also note that the use of rand is generally discouraged these days. Here is a talk by Stephan T. Lavavej on that topic.

Tags:

C++