Search code examples
c++calgorithmmath

Special simple random number generator


How to create a function, which on every call generates a random integer number? This number must be most random as possible (according to uniform distribution). It is only allowed to use one static variable and at most 3 elementary steps, where each step consists of only one basic arithmetic operation of arity 1 or 2.

Example:

int myrandom(void){
  static int x;
  x = some_step1;
  x = some_step2;
  x = some_step3;
  return x;
}

Basic arithmetic operations are +,-,%,and, not, xor, or, left shift, right shift, multiplication and division. Of course, no rand(), random() or similar stuff is allowed.


Solution

  • Linear congruential generators are one of the oldest and simplest methods:

    int seed = 123456789;
    
    int rand()
    {
      seed = (a * seed + c) % m;
      return seed;
    }
    

    Only a few instruction with basic arithmetic operations, that's all you need.

    Mind that this algorithm works fine only if a, c and m are chosen in a particular way!

    To guarantee the longest possible period of this sequence, c and m should be coprime, a − 1 should be divisible by all prime factors of m, and also for 4 if m is divisible by 4.

    Some examples of parameters are shown on Wikipedia: for example ANSI C for some compilers proposes m = 2 ³¹, a = 1103515245 and c = 12345.