Editorial for Multiple of 2019


Approach

Process the string from right to left.

Let current be the value modulo 20192019 of the suffix we have built so far, and let place be the current power of 1010 modulo 20192019. When we prepend a digit dd, the new remainder becomes (current+d⋅place) mod 2019(current + d \cdot place) \bmod 2019.

Suppose two suffixes starting at different positions give the same remainder modulo 20192019. Their difference is exactly one substring multiplied by a power of 1010. Since gcd⁡(10,2019)=1\gcd(10, 2019) = 1, multiplication by a power of 1010 is invertible modulo 20192019, so that substring itself must be divisible by 20192019.

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 kk times, then there are kk valid substrings ending at the current position range.

This runs in O(n)O(n) time and O(2019)O(2019) memory.

Solution (Python)

Code 1
s = input().strip()

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)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.