Random Gap

No attempts yetTime limit4sMemory limit128 MB

Problem

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 nn-th number RnR_n from the previous one:

Rn=(aRn1+c)modmR_n = (a \cdot R_{n-1} + c) \bmod m

where aa, cc, and mm are fixed constants and R0R_0 is the starting seed. For example, with a=15a = 15, c=7c = 7, m=100m = 100, and R0=1R_0 = 1 the sequence is 1,22,37,62,37,62,1, 22, 37, 62, 37, 62, \dots

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<RjR_i < R_j such that:

  1. no produced value RkR_k satisfies Ri<Rk<RjR_i < R_k < R_j (that is, RiR_i and RjR_j are neighbours among the distinct values), and
  2. the difference RjRiR_j - R_i is as large as possible.

Output that maximal difference. If the sequence produces only one distinct value, output 00.

Input

The input contains four integers aa, cc, mm, and R0R_0.

Output

Output a single integer: the maximal difference described above.

Constraints

  • 0a,c,R01070 \le a, c, R_0 \le 10^7
  • 1m160000001 \le m \le 16000000
  • am+c<232a \cdot m + c < 2^{32}