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?
Asked
Active
Viewed 1,118 times
1

diiN__________
- 7,393
- 6
- 42
- 69

Jay
- 161
- 1
- 18
-
2If you can use C++11, http://en.cppreference.com/w/cpp/numeric/random – Xarn Aug 30 '16 at 14:24
-
Do You use (ancient) 16 bit platform? – Jacek Cz Aug 30 '16 at 14:24
-
21) generate a number that is either 1 or 2. 2) if it is 1 generate a number between 1 and 10, if it is 2 generate a number between 1 and 10 and add 10.3) generalize for larger numbers – 463035818_is_not_an_ai Aug 30 '16 at 14:25
-
@JacekCz, for example any MSVC – RiaD Aug 30 '16 at 14:27
-
@RiaD Im surpised, but yes.C stdlih.h rand() has poor opinion, use modern (like in answers) – Jacek Cz Aug 30 '16 at 14:40
1 Answers
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
-
@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
-