Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 368
ForceBru Avatar asked Jan 23 '15 17:01

ForceBru


People also ask

Can you generate random numbers in C?

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.

What is the max value of rand () in C?

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 .

How do you generate a random number between 1 and 10 in C?

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

What does RAND () do C?

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.


2 Answers

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.

like image 111
Baum mit Augen Avatar answered Sep 29 '22 16:09

Baum mit Augen


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.

like image 20
nwellnhof Avatar answered Sep 29 '22 16:09

nwellnhof