{$APPTYPE CONSOLE}

var
  f: TextFile;
  s: array [0..$1FFFFFF] of Byte;
  i, j, a, c, m, d, maxd: Integer;
  r: Int64;
begin
  AssignFile(f, 'input.txt'); Reset(f);
  Read(f, a, c, m, r);
  CloseFile(f);
  FillChar(s, SizeOf(s), 0);
  s[r] := 1;
  for i := 1 to m + 1 do begin
    r := (a*r + c) mod m;
    s[r] := 1; //Write(r, ' ');
  end;
  j := Low(s);
  while (j <= High(s)) and (s[j] = 0) do Inc(j);
  d := 0; maxd := 0;
  for i := j to High(s) do
    if s[i] = 1 then begin
      if d > maxd then maxd := d;
      d := 1;
    end else
      Inc(d);
  AssignFile(f, 'output.txt'); Rewrite(f);
  Write(f, maxd);
  CloseFile(f);
end.
