MATH-P6

Combinations modulo a prime

Practice 6 of 7Number theory and counting10 tests

The problem

For each pair (n, k) in queries, work out C(n, k), the number of ways to choose k items from n, modulo the prime p. Return the answers as a list, in the same order. C(n, k) is 0 when k is bigger than n.

comb_mod([(5, 2), (6, 3), (4, 0)], 1_000_000_007)
# [10, 20, 1]
comb_mod([(3, 5)], 1_000_000_007)    # [0]

math.comb, math.factorial and math.perm are switched off. pow is allowed.

Limits

  • Up to 100,000 queries, with 0 ≤ k and n up to 1,000,000. p is a prime bigger than every n.
  • Working out each answer from scratch is too slow for 100,000 queries. The big tests have 6 seconds each.

Builds on MATH-6 Combinations and Pascal’s triangle.

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.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2More than nNot run
3Nothing from nothingNot run
4Row 10Not run
5A big countNot run
6Another primeNot run
7A small primeNot run
8No queriesNot run
9100,000 queriesNot run
10The middle of row 10⁶Not run