Under construction

Still being built. Things may change

Gems in the maze

Interview

Time limit3sMemory limit2048 MB

Summary
Find the longest run of distinct chambers reachable by repeatedly following the tunnel from v to (a*v^2 + b*v + c) mod n.
Level

Medium4 of 10

Topics
Graph, DFS, Array
Solved
No attempts yet

Problem

Scrooge McDuck has a new plan to increase his wealth. He found ancient ruins with an extraordinary maze. The maze consists of nn chambers numbered 00 through n−1n - 1. Each chamber contains exactly one gem. Chambers are connected by one-way tunnels. Each chamber has exactly two outgoing tunnels: one leads to the chamber numbered (a⋅v2+b⋅v+c) mod n(a \cdot v^2 + b \cdot v + c) \bmod n, and the other brings you out of the maze.

You can enter the maze at any chamber, move along the tunnels, and collect the gems. Once you leave the maze, the self-destruct mechanism triggers, the ceiling collapses, and every gem you did not collect is lost forever.

Scrooge wants to know the maximum number of gems he can take from the maze.

Input

The first line of the input contains four integers aa, bb, cc, and nn, which describe one particular maze.

Output

Output a single line containing one integer: the maximum number of gems that can be taken from the maze.

Hint

The starting chamber matters. For instance, in the first test case Scrooge starts in chamber 00. His only two options are a tunnel that leads back to chamber 00 and a tunnel that leads outside, which is not much of a choice. A much better strategy is to start in chamber 22 and follow the path 2→8→16→32→0→2 \rightarrow 8 \rightarrow 16 \rightarrow 32 \rightarrow 0 \rightarrow outside.

Examples3

  1. Example 1

    Input
    1 2 0 64
    
    Expected output
    5
    
  2. Example 2

    Input
    0 2 1 47
    
    Expected output
    23
    
  3. Example 3

    Input
    0 3 5 128
    
    Expected output
    64