1

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?

diiN__________
  • 7,393
  • 6
  • 42
  • 69
Jay
  • 161
  • 1
  • 18

1 Answers1

3

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.

Xirema
  • 19,889
  • 4
  • 32
  • 68
  • 1
    Writing numbers like `1'000'000` is allowed? – Arnav Borborah Aug 30 '16 at 14:32
  • @ArnavBorborah Not sure when it became a thing (I think C++14?) but the apostrophe symbol is allowed to be used as a separator in numbers. – Xirema Aug 30 '16 at 14:32
  • Yes, this came about in C++14. "Optional single quotes(') may be inserted between the digits as a separator. They are ignored by the compiler. (since C++14)" (http://en.cppreference.com/w/cpp/language/integer_literal). – Fred Larson Aug 30 '16 at 14:37
  • @FredLarson Thanks for clearing that up, also thanks Xirema – Arnav Borborah Aug 30 '16 at 14:41