Competitive programming

Stage 2 of 10 · 6 lessons · ~3 weeks

Maths basics

Learn the number theory easier contests use: modular arithmetic, gcd, primes and divisors, fast powers, and spotting invariants such as parity.

Start: Modular arithmetic

Lessons· one lesson for each topic, in this order

  1. 1Modular arithmetic
  2. 2GCD, LCM and Euclid's algorithm
  3. 3Primes and the sieve
  4. 4Factorisation and divisors
  5. 5Fast exponentiation
  6. 6Parity and invariants

Do this

  • Write modular add, subtract and multiply helpers and test them with negative results.
  • Write fast exponentiation from memory and check it against a slow loop.
  • Write a sieve up to 10^7 and time it.
  • Solve 5 CSES Mathematics problems.
  • Solve 5 Codeforces problems tagged number theory near your rating.
  • For one parity or invariant problem, write down the invariant before coding.

Start with

  • BookFree
    Competitive Programmer's Handbook

    Antti Laaksonen · Beginner

    Section 1.5 covers the maths basics and Chapter 21 covers number theory, from primes to modular inverses

Practise

  • The Mathematics section: exponentiation, counting divisors and binomial coefficients

  • Filter the problem set by the number theory and math tags, near your rating

Keep handy

Also worth your time

Before moving on: Fast power, sieve and trial division written from memory, and 10 maths problems solved across CSES Mathematics and Codeforces problems tagged number theory at your level.

Tauseef's advice
Contest maths is a small toolkit used often, not a degree. Modular arithmetic, gcd, primes and fast power come up constantly, so make them automatic. When a problem looks like maths, try small cases by hand first: the pattern is usually visible by n = 6.

Mark this stage as not done?