## Marsaglia’s Mental RNG

### January 29, 2019

We saw an “in-your-head” random number generator in a previous exercise, but I found it hard to operate. Today’s exercise, due to George Marsaglia is a random number generator that even a dummy like me can work in his head:

Choose a two-digit number as a seed. Then form a new two-digit number by adding the ten’s digit and six times the unit digit. For instance, if you start from 23, the sequence is 23 → 20 → 02 → 12 → 13 → 19 → 55 → 35 …. Then the sequence of random digits is the unit digit of each two-digit number. This operation produces the numbers 1 through 58 as seeds; the ten digits each occur six times, except that nine and zero occur five times (because 59 and 60 are not part of the sequence).

Your task is to implement Marsaglia’s mental RNG, and experiment with it to determine its effectiveness. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

I found the last digits were not distributed randomly. For a sequence of 10000 numbers the digits 1…8 appeared 1035 +- 2 times while 0 and 9 appeared ~862 times

Here’s a Python version as a generator:

I’m not sure it’s a particularly good PRNG, as each seed simply produces the same sequence in rotation, but it certainly is simple to use.

Note: DO NOT use 59 as the seed :)

Well, it’s a pretty good RNG considering it’s only got 6 bits of state! If the shortage of 0 and 9 is bothersome, you can always skip values greater than 50:

It’s interesting to generalize a bit and work in base b (this is a lag-1 Multiply with Carry RNG, as Praxis says). The inverse operation to bx + y -> ay + x is just n -> bn mod (ab-1) ie. the sequence, starting and ending at 1 is just the reverse of the sequence 1,b,b^2,b^3,… taking each element mod m = ab-1 so the period is the period of b, mod m. For a given b, this is longest when m is a prime and b is a primitive root mod m, and we do particularly well if we can take a = b-1 since the sequence then covers nearly all of the range [1..b*b]. For example, for b = 127, a = 126, we get a sequence of length 16000 including all but 129 of the 16129 two digit base-127 numbers. Here’s a program that calculates such maximal sequences:

Like 127, 999 is interesting (this is a CMWC generator, I believe):

I don’t think that sequence is in the OEIS.

Here’s a solution in C.

Example usage:

$ ./a.out 32 10

2

5

1

9

4

9

6

1

0

1