progress

~/problems / Number theory / Modular arithmetic

Dividing under a prime modulus

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Many problems say "the answer is a fraction p / q; give it modulo MOD = 1_000_000_007". That means the x in [0, MOD) with x · q ≡ p (mod MOD), i.e. p · q⁻¹ mod MOD. Plain p // q or p / q won't do: there are no floats here, and integer division doesn't commute with %.

Write:

  1. frac_mod(p: int, q: int) -> int: p / q modulo MOD. Either may be negative or huge; q is never a multiple of MOD.
  2. average_mod(nums: list[int]) -> int: the average of a non-empty list, modulo MOD.
frac_mod(6, 3)        # 2
frac_mod(1, 2)        # 500000004   (2 · 500000004 = 1000000008 ≡ 1)
frac_mod(-1, 2)       # 500000003
average_mod([1, 2])   # 500000005   (3/2)
average_mod([4, 4, 7])  # 5

MOD is prime, so Fermat's little theorem gives q⁻¹ ≡ q^(MOD-2): pow(q, MOD - 2, MOD) in Python. Python's % already lands in [0, MOD).

Values up to 10^18 in size; up to 10^5 numbers.

Show hint

division mod a prime is multiplying by the inverse: p * pow(q, MOD - 2, MOD) % MOD.

Topic: Modular arithmetic. Fast exponentiation, Fermat inverses, nCr mod p with factorial tables.

0:00
Ctrl ' run · Ctrl ↵ submit
esc