Standard rand()
function gives numbers not big enough for me: I need unsigned long long
ones. How do we get really big random numbers? I tried modifying a simple hash function but it's too big, takes too long to run and never produces numbers which are less than 1e5!!
In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.
The value of this macro is an integer constant representing the largest value the rand function can return. In the GNU C Library, it is 2147483647 , which is the largest signed integer representable in 32 bits. In other libraries, it may be as low as 32767 .
You can start to call at the beginning of your program: srand(time(NULL)); Note that % 10 yields a result from 0 to 9 and not from 1 to 10 : just add 1 to your % expression to get 1 to 10 . @Nisarg; Use srand((unsigned)time(NULL)) .
rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
You can easily do this with std::uniform_int_distribution<unsigned long long>
.
Simple example code (taken from here, modified to use unsigned long long
):
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned long long> dis(lowerBorder, upperBorder);
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
Note that the seeding of the mersenne twister as done here for demo purposes is not perfect, for example see here.
Here's a portable C99 solution that returns a random 64-bit number:
unsigned long long llrand() {
unsigned long long r = 0;
for (int i = 0; i < 5; ++i) {
r = (r << 15) | (rand() & 0x7FFF);
}
return r & 0xFFFFFFFFFFFFFFFFULL;
}
Explanation: rand()
returns integers in the range 0 to RAND_MAX
and RAND_MAX
is only guaranteed to be at least 32,767 (15 random bits). long long
is guaranteed to have 64 bits but may be larger.
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