Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random long number

Tags:

c++

I know that to generate random long number, I do following steps in Java:

Random r = new Random();
return r.nextLong();

What will be equivalent of this code in C++? like this?

return (long)rand();
like image 670
user439547 Avatar asked Sep 08 '10 06:09

user439547


People also ask

How do you generate a long random number?

We can generate random long values with the nextLong method of the RandomUtils class. nextLong is a static method that can generate random long values. There are two variations of the method: One takes the range as parameters and generates random long values within the specified range.

How do you generate a random long number within a range in Java?

In order to generate Random long type numbers in Java, we use the nextLong() method of the java. util. Random class. This returns the next random long value from the random generator sequence.

Why is 17 the most common random number?

Seventeen is: Described at MIT as 'the least random number', according to the Jargon File. This is supposedly because in a study where respondents were asked to choose a random number from 1 to 20, 17 was the most common choice. This study has been repeated a number of times.

How do you generate a random number between 1000 and 9999 in Java?

How do you generate a random number between 1000 and 9999 in Java? int randomNumber = ( int )( Math. random() * 9999 ); if( randomNumber <= 1000 ) { randomNumber = randomNumber + 1000; Math. random() is a method that generates a random number through a formula.


1 Answers

<cstdlib> provides int rand(). You might want to check out the man page. If long is bigger than int on your system, you can call rand() twice and put the first value in the high word.

#include <cstdlib>

long lrand()
{
    if (sizeof(int) < sizeof(long))
        return (static_cast<long>(rand()) << (sizeof(int) * 8)) |
               rand();

    return rand();
}

(it's very unlikely that long is neither the same as or double the size of int, so this is practical if not theoretically perfect)

Check your docs for rand() though. It's not a great generator, but good enough for most things. You'll want to call srand() to initialise the random-number generation system. Others have commented that Windows doesn't return sizeof(int) randomised bits, so you may need to tweak the above.

like image 121
Tony Delroy Avatar answered Sep 23 '22 18:09

Tony Delroy