Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out what a random number generator was seeded with in C++

I've got an unmanaged c++ console application in which I'm using srand() and rand(). I don't need this to solve a particular problem, but was curious: is the original seed passed to srand() stored somewhere in memory that I can query? Is there any way to figure out what the seed was?

like image 786
Brian Avatar asked Aug 27 '09 19:08

Brian


People also ask

What is the seed for random number generator?

Python Random seed() Method The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time.

What is Srand () in C?

General description. srand() uses its argument seed as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is not called, the rand() seed is set as if srand(1) was called at program start. Any other value for seed sets the generator to a different starting point.

How do you identify a random number generator?

There are two phases to test the random number generator process. First you need a source of entropy[1] that is impossible to guess like the weather. Second you need a deterministic algorithm to expand the seed into a multitude of sequences for keys and the like. Testing usually starts with checking your entropy.

What is difference between rand () and Srand ()?

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.


2 Answers

The seed is not required to be stored, only the last random number returned is.

Here's the example from the manpage:

       static unsigned long next = 1;

       /* RAND_MAX assumed to be 32767 */
       int myrand(void) {
           next = next * 1103515245 + 12345;
           return((unsigned)(next/65536) % 32768);
       }

       void mysrand(unsigned seed) {
           next = seed;
       }
like image 144
P Shved Avatar answered Nov 11 '22 01:11

P Shved


If you have a simple linear congruential generator, for which you have several values this yields a system of equations:

 v1 = ( seed * a + b ) % m
 v2 = (   v1 * a + b ) % m;
 v3 = (   v2 * a + b ) % m;
... 

If you know the first value, you can go backwards in the sequence:

seed = (v1 - b)/a (mod m)

You don't know the seed uniquely, you only know it mod m (which is usually fine since (0 < seed < m) anyways) If v1 - b is negative you need to add m's until its positive again.

You might also look at the Chinese Remainder Theorem, though its not an exact match.

like image 38
Justin Avatar answered Nov 11 '22 00:11

Justin