<?xml version="1.0" encoding="Windows-1251"?>
<CATS version="1.0">
<Problem title="Random Gap" lang="en" author="A. Klenin" tlimit="8" mlimit="2"
    inputFile="input.txt" outputFile="output.txt" stdChecker="nums">

<ProblemStatement>
<p>The pseudo-random number genegators (or RNGs for short) are widely used in statistical calculations.
One of the simplest and ubiquitious is the linear congruence RNG, that calculates the <i>n</i>-th
random number <i>R<sub>n</sub></i> as
<i>R<sub>n</sub></i> = (<i>aR</i><sub><i>n</i> - 1</sub> + <i>c</i>) mod <i>m</i>,
where <i>a</i>, <i>c</i> and <i>m</i> are constants.
For example, the sequence for <i>a</i> = 15, <i>c</i> = 7, <i>m</i> = 100 and
starting value <i>R</i><sub>0</sub> = 1 is 1, 22, 37, 62, 37, 62, ...
</p>
<p>Linear RNG is very fast, and can yield surprisinly good sequence of random numbers, given
the right choice of constants. There are various measures of RNG quality,
and your task is to calculate one of them, namely the longest gap between members of the sequence.
More precisely, given the values of <i>a</i>, <i>c</i>, <i>m</i>, and <i>R</i><sub>0</sub>, 
find such two elements <i>R<sub>i</sub></i> &lt; <i>R<sub>j</sub></i> that:
<ol>
  <li>there are no other <i>R<sub>k</sub></i>
    <i>R<sub>i</sub></i> &amp;le; <i>R<sub>k</sub></i> &amp;le; <i>R<sub>j</sub></i>,</li>
  <li>the difference <i>R<sub>j</sub></i> &amp;minus; <i>R<sub>i</sub></i> is maximal.</li>
</ol>
</p>
</ProblemStatement>

<InputFormat>
Input file contains integer numbers <i>a</i> <i>c</i> <i>m</i> <i>R</i><sub>0</sub>.
</InputFormat>

<OutputFormat>
Output file should contain the single number -- the maximal difference found.
</OutputFormat>

<ProblemConstraints>
0 &amp;le; <i>a</i>, <i>c</i>, <i>R</i><sub>0</sub> &amp;le; 10<sup>7</sup>,
1 &amp;le; <i>m</i> &amp;le; 16000000,
<i>a</i><i>m</i> + <i>c</i> &lt; 2<sup>32</sup>.
</ProblemConstraints>

<Sample rank="1">
  <SampleIn>15 7 100 1</SampleIn>
  <SampleOut>25</SampleOut>
</Sample>
<Sample rank="2">
  <SampleIn>2 0 127 5</SampleIn>
  <SampleOut>26</SampleOut>
</Sample>

<Solution name="sol" src="rng.dpr"/>
<TestRange from="1" to="14"><In src="t%0n"/><Out use="sol"/></TestRange>

</Problem>
</CATS>