kahheng kahheng - 3 months ago 23
C++ Question

c++ How to generate random number between 1 and 10^6?

I realize that the maximum number

rand()
can generate is 32767. Is there anyway I can generate random numbers with value between 1 and 10^6(1 million) without external libraries?

Answer

Not sure what you mean by "external libraries" but it's quite easy with the C++11 random library.

std::default_random_engine engine{std::chrono::steady_clock::now().time_since_epoch().count()};
std::uniform_int_distribution<int> range{1, 1'000'000};

int randomly_generated_number = range(engine);
int another_randomly_generated_number = range(engine);

For general purpose random numbers, I'd probably recommend using std::mt19937 (or std::mt19937_64 on 64-bit machines) instead of std::default_random_engine but the default engine is better for learning purposes.