Pseudo-Random Numbers

Interview

Time limit1sMemory limit128 MB

Summary
For each quadruple (Z, I, M, L), follow the recurrence L = (Z*L + I) mod M and report how many distinct values appear before the sequence starts repeating.
Level

Medium4 of 10

Topics
Hash map, Simulation, Math, Implementation
Solved
No attempts yet

Problem

Computers normally cannot generate truly random numbers, but they are frequently used to generate sequences of pseudo-random numbers. These are produced by some algorithm, but for all practical purposes they appear to be truly random. Random numbers are used in many applications, including simulation.

A common pseudo-random number generation technique is the linear congruential method. If the last pseudo-random number generated was LL, then the next number is generated by evaluating (Z×L+I) mod M(Z \times L + I) \bmod M, where ZZ is a constant multiplier, II is a constant increment, and MM is a constant modulus.

For example, suppose Z=7Z = 7, I=5I = 5, and M=12M = 12. If the first random number (usually called the seed) is 44, then the next few pseudo-random numbers are determined as follows:

Last Random Number, L | (Z×L+I) | Next Random Number, (Z×L+I) mod M
----------------------|---------|----------------------------------
         4            |   33    |                9
         9            |   68    |                8
         8            |   61    |                1
         1            |   12    |                0
         0            |    5    |                5
         5            |   40    |                4

As you can see, the sequence of pseudo-random numbers generated by this technique repeats after six numbers. It should be clear that the longest sequence that can be generated using this technique is limited by the modulus MM.

In this problem you are given sets of values for ZZ, II, MM, and the seed LL. Each of these has no more than four digits. For each set of values, determine the length of the cycle of pseudo-random numbers that will be generated. But be careful — the cycle might not begin with the seed!

Input

Each input line contains four integer values, in order: ZZ, II, MM, and LL. The last line contains four zeroes and marks the end of the input data. LL is always less than MM.

Output

For each input line, print one line in the format Case N: L, where NN is the case number (numbered sequentially starting from 1) and LL is the length of the sequence of pseudo-random numbers before it begins to repeat.

Examples1

  1. Example 1

    Input
    7 5 12 4
    5173 3849 3279 1511
    9111 5309 6000 1234
    1079 2136 9999 1237
    0 0 0 0
    
    Expected output
    Case 1: 6
    Case 2: 546
    Case 3: 500
    Case 4: 220