I want to generate very large random number in range of 0 - 2^64 using c++. I have used the rand() function but it is not generating very large number. Can any one help?
For random number generator in C, we use rand() and srand() functions that can generate the same and different random numbers on execution.
In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.
The answer is simple: use std::random_device to generate a single random number which is then used as a seed for a pseudorandom number generator (PRNG) and then use the PRNG itself to generate as many pseudorandom numbers as we wish.
1.1. The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.
With c++11, using the standard random library of c++11, you can do this:
#include <iostream>
#include <random>
int main()
{
/* Seed */
std::random_device rd;
/* Random number generator */
std::default_random_engine generator(rd());
/* Distribution on which to apply the generator */
std::uniform_int_distribution<long long unsigned> distribution(0,0xFFFFFFFFFFFFFFFF);
for (int i = 0; i < 10; i++) {
std::cout << distribution(generator) << std::endl;
}
return 0;
}
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With