I'm trying to generate n
digit random numbers. I can generate a random number, but here the case is to generate a n
digit number.
I tried doing it by storing the random numbers in an array but I need it in a long long format and not an array.
-
1Hint: `n`-digit numbers are those from `10^(n-1)` to `10^n-1`. – ivan_pozdeev Mar 14 '16 at 03:17
-
3If you have an elementary education in math, you should know how to turn an array of digits into the corresponding number. All you need to know is that "532" is 5x100 + 3x10 + 2x1. – David Schwartz Mar 14 '16 at 03:18
-
@DavidSchwartz in this case, the distribution won't be uniform. He didn't specify if it needs to be though. – ivan_pozdeev Mar 14 '16 at 03:19
-
How big can `n` be? Will it fit inside a 32- or 64-bit integer? – paddy Mar 14 '16 at 03:23
-
@davidschwartz, I didn't learn that in elementary school. – nicomp Mar 14 '16 at 03:34
1 Answers
There are two things you need to do:
- Work out how to output random numbers within a given range
- Work out what range you need in order to get only 10-digit numbers
Part (1) is actually a bit tricky, if you want to ensure every number in your range is equally likely to occur. Fortunately, the standard library in C++11 onwards comes with a facility called uniform_int_distribution
which does the required calculations for you:
// Create and seed the random number generator
auto gen = std::mt19937{std::random_device{}()};
// Create our desired distribution
auto dist = std::uniform_int_distribution<int_type>{lower, upper};
// Get numbers
std::cout << dist(gen) << "\n";
For part (2), we need to work out what lower
and upper
should be above. That's actually pretty easy: the lowest 10-digit number is 1,000,000,000 (one billion), and the highest is 9,999,999,999 (one less than 10 billion). We can put these numbers straight in to C++
constexpr auto lower = 1'000'000'000;
constexpr auto upper = 9'999'999'999;
(Note you'll need a C++14 compiler to use '
as a digit separator).
Now, there's one last problem: on a typical system, lower
and upper
above will be different types, because lower
will fit into an int
but upper
will not. So we need to make sure that our output uses the larger of the two types. A good way to do this is to use a type alias and decltype
:
using int_type = decltype(upper);
This says we are declaring a new type name int_type
which is an alias for the type of upper
.
Put these together and you'll have a routine that will output 10 digit numbers on any system that uses C++11.
![](../../users/profiles/2797826.webp)
- 15,036
- 2
- 31
- 79