Editorial for Multiple of 2019
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Process the string from right to left.
Let current be the value modulo of the suffix we have built so far, and let
place be
the current power of modulo
. When we prepend a digit
, the new remainder becomes
.
Suppose two suffixes starting at different positions give the same remainder modulo .
Their difference is exactly one substring multiplied by a power of
. Since
, multiplication by a power of
is invertible modulo
, so that
substring itself must be divisible by
.
Therefore, as we scan from right to left, we only need to count how many times each remainder has
appeared before. If the current remainder has already appeared times, then there are
valid
substrings ending at the current position range.
This runs in time and
memory.
Solution (Python)
import sys
s = sys.stdin.buffer.readline().strip().decode()
counts = [0] * 2019
counts[0] = 1
answer = 0
current = 0
place = 1
for ch in reversed(s):
current = (current + (ord(ch) - ord("0")) * place) % 2019
answer += counts[current]
counts[current] += 1
place = (place * 10) % 2019
print(answer)
Comments