{$APPTYPE CONSOLE}

var
  f: TextFile;
  s: array [0..1800000] of Byte;
  i, j, a, c, m, d, maxd, r0, ub, lb: Integer;
  r: Integer;
begin
//  AssignFile(f, 'input.txt'); Reset(f);
  Read(a, c, m, r0);
//  CloseFile(f);
  maxd := 0; d := 0; lb := 0; ub := High(s);
  while lb < m do begin
    FillChar(s, SizeOf(s), 0);
    r := r0;
    if (lb <= r) and (r <= ub) then s[r - lb] := 1;
    for i := 1 to m + 1 do begin
      r := (a*r + c) mod m;
      if (lb <= r) and (r <= ub) then s[r - lb] := 1;
      //Write(r, ' ');
    end;
    j := Low(s);
    while (j <= High(s)) and (s[j] = 0) do Inc(j);
    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);
    lb := ub + 1;
    Inc(ub, Length(s));
  end;
//  AssignFile(f, 'output.txt'); Rewrite(f);
  Write(maxd);
//  CloseFile(f);
end.
