Find the Multiples

Time limit2sMemory limit128 MB

Summary
Count index pairs (i,j) with a_i nonzero such that the decimal number formed by a_i...a_j is divisible by a given prime Q, for a pseudo-randomly generated digit sequence of length up to 1e5.
Level

Medium7 of 10

Topics
Math, Hash map, Number theory, Prefix sum
Solved
No attempts yet

Problem

You are given a sequence of digits a0a1⋯aN−1a_0 a_1 \cdots a_{N-1} and a prime number QQ. For every pair of indices i≤ji \le j with ai≠0a_i \ne 0, the subsequence aiai+1⋯aja_i a_{i+1} \cdots a_j can be read as the decimal representation of a positive integer. Subsequences with a leading zero (that is, with ai=0a_i = 0) are not considered. Your task is to count the number of pairs (i,j)(i, j) for which the corresponding integer is a multiple of QQ.

Input

The input consists of at most 5050 datasets. Each dataset is a single line with four integers NN, SS, WW, and QQ separated by spaces, where 1≤N≤1051 \le N \le 10^5, 1≤S≤1091 \le S \le 10^9, 1≤W≤1091 \le W \le 10^9, and QQ is a prime number smaller than 10810^8. The sequence a0⋯aN−1a_0 \cdots a_{N-1} of length NN is produced by the following code, where aia_i is written as a[i]:

int g = S;
for(int i=0; i<N; i++) {
    a[i] = (g/7) % 10;
    if( g%2 == 0 ) { g = (g/2); }
    else           { g = (g/2) ^ W; }
}

Here /, %, and ^ are integer division, modulo, and bitwise exclusive-or, respectively. This code is only a pseudo-random generator; the intended solution does not depend on how the sequence is generated.

The end of the input is indicated by a line containing four zeros separated by spaces.

Output

For each dataset, output the answer on its own line. You may assume that the answer is smaller than 2302^{30}.

Hint

The same number is counted once for each pair of positions (i,j)(i, j) that produces it. For example, if the sequence is 421421 and Q=7Q = 7, the multiples of 77 are 4242 and 2121, so the answer is 22. If the sequence is 50525052 and Q=5Q = 5, the multiples of 55 are 55, 5050, 505505, and 55 again, for a total of 44. The values 00 and 0505 are not counted, because a considered subsequence must start at a nonzero digit (no leading zeros) and represent a positive integer; the digit 55 is counted twice because it appears at two different positions. For reference, the first four datasets of the sample input generate the sequences 421421, 50525052, 9507395073, and 1222112221.

Examples3

  1. Example 1

    Input
    3 32 64 7
    4 35 89 5
    5 555 442 3
    5 777 465 11
    100000 666 701622763 65537
    0 0 0 0
    
    Expected output
    2
    4
    6
    3
    68530
    
  2. Example 2

    Input
    20 100 200 7
    0 0 0 0
    
    Expected output
    31
    
  3. Example 3

    Input
    30 5 5 2
    30 5 5 5
    0 0 0 0
    
    Expected output
    60
    60