-2

I don't know what the heck all this is about. All I know about is that it's a function that produces random number.

So can you explain this whole entire piece of code to me. This is page 46 in K&R C programming language 2nd edition book.

unsigned long int next = 1;

/* rand: return pseudo-random integer on 0..32767 */
int rand(void)
{
    next = next * 1103515245 + 12345;   /*What the heck is this line doing?????? */
    return (unsigned int) (next/65536) % 32768; /*This line, too, I have no idea.. */
}

/* srand: set seed for rand() */
void srand(unsigned int seed)
{
     next = seed;
}
James
  • 43
  • 8
  • possible duplicate of [Why 1103515245 is used in rand?](http://stackoverflow.com/questions/8569113/why-1103515245-is-used-in-rand) – Macattack Nov 27 '13 at 05:56

1 Answers1

0

This random number generator consists an LCG, which are algorithms of the form Xn+1 (the next element) = aXn+c mod m (Xn is the current element). It then takes the 15 bits starting from the second bit of the seed as output. In an LCG, each number is produced by multiplying the state number by a constant, adding it to a constant and moduloing it a constant, which will determine the size of the output.

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44