
I took MA1301 at NTNU this semester and honestly didn’t expect it to help much with competitive programming. Turns out number theory is everywhere in contest problems. Here are the key concepts that actually made my solutions faster and cleaner.
Modular Arithmetic That Actually Works
Contest problems love throwing around huge numbers and asking for results modulo $10^9+7$. If you try to compute something like $2^{1000000}$ the normal way, you’re going to have a bad time. Fast modular exponentiation saves the day:
1 | def mod_pow(base: int, exponent: int, modulus: int) -> int: |
Fermat’s Little Theorem Is Actually Useful
Fermat’s Little Theorem says that for a prime $p$ and any integer $a$ not divisible by $p$:
$$a^{p-1}\equiv 1\pmod{p}$$
This is super handy for computing modular inverses. Instead of doing division in modular arithmetic (which is messy), you can multiply by the inverse:
1 | def mod_inverse(a: int, m: int) -> int: |
Chinese Remainder Theorem
Sometimes you get problems with multiple modular constraints that look impossible. The Chinese Remainder Theorem handles systems like:
$$x \equiv a_1 \pmod{m_1}$$
$$x \equiv a_2 \pmod{m_2}$$
$$\vdots$$
$$x \equiv a_n \pmod{m_n}$$
Here’s how to solve them:
1 | def chinese_remainder(remainders: list[int], moduli: list[int]) -> int: |
Euler’s Totient Function
Euler’s totient function $\phi(n)$ counts how many numbers less than or equal to $n$ are coprime to $n$. The formula is:
$$\phi(n) = n\prod_{p|n}\left(1-\frac{1}{p}\right)$$
This shows up in problems about counting coprime pairs or when you need to apply Euler’s theorem for modular exponentiation.
When I Actually Use This Stuff
These concepts pop up more than you’d expect:
Chinese Remainder Theorem: Perfect for problems where you have multiple modular constraints that seem impossible to satisfy simultaneously.
Euler’s totient function: Great for counting problems involving coprime numbers or when you need to find patterns in modular exponentiation.
Fast modular arithmetic: Essential whenever you see big numbers and a modulus in the problem statement.
What I Learned
Number theory transforms what look like impossible problems into straightforward algorithms. The math might seem abstract at first, but once you see how it applies to actual contest problems, it becomes incredibly practical.
I’ve used these techniques in several contest solutions that you can check out in my competitive programming repository. The difference in both code clarity and performance is pretty significant.
If you want to discuss any of these concepts or have questions about specific applications, feel free to reach out.