-2

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.

Prasad
  • 1,544
  • 5
  • 23
  • 39
Grat
  • 83
  • 1
  • 1
  • 7

1 Answers1

1

There are two things you need to do:

  1. Work out how to output random numbers within a given range
  2. 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.

Tristan Brindle
  • 15,036
  • 2
  • 31
  • 79