c++crandomunsigned-long-long-int

Getting big random numbers in C/C++


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!!


Solution

  • 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.