Pseudo-random number generators (RNGs) are widely used in statistical computing. One of the simplest and most common is the linear congruential generator, which produces the n-th number Rn from the previous one:
Rn=(a⋅Rn−1+c)modm
where a, c, and m are fixed constants and R0 is the starting seed. For example, with a=15, c=7, m=100, and R0=1 the sequence is 1,22,37,62,37,62,…
Such generators are fast and, with well-chosen constants, produce good random sequences. One measure of quality is the longest gap between the values the sequence produces. Consider the set of distinct values that appear in the sequence, and find two of them Ri<Rj such that:
Output that maximal difference. If the sequence produces only one distinct value, output 0.
The input contains four integers a, c, m, and R0.
Output a single integer: the maximal difference described above.