Out of Sorts

Time limit1sMemory limit512 MB

Summary
Given a linear congruential sequence of n distinct values, count how many of those values a binary search on the unsorted array would actually find.
Level

Medium7 of 10

Topics
Divide and conquer, Binary search, Implementation, Math
Solved
No attempts yet

Problem

Ann Logan is fascinated with finite sequences of integers. She is particularly interested in sequences of the form x1,x2,…,xnx_1, x_2, \ldots, x_n where:

  • xi=(axi−1+c) mod mx_i = (a x_{i-1} + c) \bmod m,
  • n,m,an, m, a, and cc are positive integer constants,
  • x0x_0 is a non-negative integer constant, and
  • all nn values are distinct.

For example, if n=5n = 5, m=8m = 8, a=1a = 1, c=3c = 3, and x0=3x_0 = 3, the sequence is 6,1,4,7,26, 1, 4, 7, 2 (x1=(1⋅3+3) mod 8=6x_1 = (1 \cdot 3 + 3) \bmod 8 = 6, x2=(1⋅6+3) mod 8=1x_2 = (1 \cdot 6 + 3) \bmod 8 = 1, and so on). She does not count the initial value x0x_0 as part of the sequence.

Ann wants to determine quickly, for any integer value, whether it appears in a finite sequence of this form. Given values of n,m,a,cn, m, a, c, and x0x_0, she plans to follow this list of steps:

  1. Generate the sequence x1,…,xnx_1, \ldots, x_n and store it in an array.
  2. Sort the array.
  3. Perform a binary search of the array for each integer of interest.

Ann's search algorithm is not the most efficient possible, but it is straightforward and understandable to anyone familiar with binary search. At each step, after computing the midpoint with mid=(low+high)/2mid = (low+high)/2, she first checks whether the value at position midmid equals the search value xx. If not, she narrows the search according to whether xx is strictly less than or strictly greater than the value at position midmid.

Unfortunately, Ann is absent-minded and lost her list of steps. She remembered the first and last step, but she forgot to sort the array before performing the binary search. Naturally, many values present in the unsorted array cannot be found by a binary search, though surprisingly some can. In the example above, both 4 and 7 can be found with Ann's binary search. How many values can be found for various sequences? Don't botch it up!

Input

The input consists of a line containing five integers n,m,a,cn, m, a, c, and x0x_0 (1≤n≤1061 \le n \le 10^6, 1≤m,a,c≤231−11 \le m, a, c \le 2^{31} - 1, 0≤x0≤231−10 \le x_0 \le 2^{31} - 1). nn is the length of the sequence x1,…,xnx_1, \ldots, x_n to be generated, and m,a,cm, a, c, and x0x_0 are the constants used to generate the sequence. All values in the generated sequence are guaranteed to be distinct.

Output

Output the number of sequence values that can be found with Ann's binary search, assuming she forgot to sort the sequence.

Examples2

  1. Example 1

    Input
    5 8 1 3 3
    
    Expected output
    2
    
  2. Example 2

    Input
    6 10 1234567891 1 1234567890
    
    Expected output
    6