ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
def div_count(a, k):
    cnt = {0: 1}
    s = 0
    ans = 0
    for x in a:
        s = (s + x) % k
        ans += cnt.get(s, 0)
        cnt[s] = cnt.get(s, 0) + 1
    return ans
print(div_count([4, 5, 0, -2, -3, 1], 5), (-7) % 3)
  1. A. 7 -3
  2. B. 7 2
  3. C. 5 2
  4. D. 7 1

Correct answer: B. 7 2

Prefix sums taken modulo k with Python's % stay in 0 to k-1 even for negative numbers, so equal remainders mark a subarray whose sum is divisible by k. The example gives 7, and (-7) % 3 is 2.

More Python Programming questions

Exams that ask this topic