MATH-P2

Pairs that add to a multiple

Practice 2 of 7Number theory and counting12 tests

The problem

Return how many pairs of positions i < j in the list a have a sum a[i] + a[j] that is a multiple of k.

pairs_to_multiple([1, 2, 3, 4, 5], 3)   # 4
pairs_to_multiple([-1, 1, -5, 7], 6)    # 3
pairs_to_multiple([5] * 10, 10)         # 45

Limits

  • a has up to 200,000 whole numbers, which may be negative and may be very large. k is from 1 to about a million.
  • Checking every pair is far too slow for 200,000 numbers (about 20 billion pairs). The big tests have 3 seconds each.

Builds on MATH-2 Modular arithmetic.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No valuesNot run
3k is 1Not run
4All remainder 0Not run
5Remainder k/2Not run
6Negative valuesNot run
7Repeated valueNot run
8Big valuesNot run
92,000 valuesNot run
10200,000 valuesNot run
11k is 2Not run
12All multiples of 7Not run