Find the Multiples
Time limit2sMemory limit128 MB
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 and a prime number . For every pair of indices with , the subsequence can be read as the decimal representation of a positive integer. Subsequences with a leading zero (that is, with ) are not considered. Your task is to count the number of pairs for which the corresponding integer is a multiple of .
Input
The input consists of at most datasets. Each dataset is a single line with four integers , , , and separated by spaces, where , , , and is a prime number smaller than . The sequence of length is produced by the following code, where 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 .
Hint
The same number is counted once for each pair of positions that produces it. For example, if the sequence is and , the multiples of are and , so the answer is . If the sequence is and , the multiples of are , , , and again, for a total of . The values and are not counted, because a considered subsequence must start at a nonzero digit (no leading zeros) and represent a positive integer; the digit is counted twice because it appears at two different positions. For reference, the first four datasets of the sample input generate the sequences , , , and .