Foundation · Module 2 · Lesson 3
Modular arithmetic
Overflow-safe arithmetic and cyclic values.
15–25 min readLesson 9 of 123
Lesson 9 of 123
1d streakTheory lesson · Step-by-step
Understand Modular arithmetic
Overflow-safe arithmetic and cyclic values.
Worked approach
Trace the reasoning step by step
- 1Write the relevant identity or bit property for Modular arithmetic.
- 2Normalize signs, ranges, and overflow-sensitive values before calculating.
- 3Apply one valid transformation and verify the identity still holds.
- 4Stop at the simplest base form, then translate the result back to the requested output.
- 5Test zero, one, negative values, repeated factors, and numeric limits.
Concrete example
Compute 3¹³ mod 7 without constructing 3¹³.
- 13¹ ≡ 3
- 23² ≡ 2
- 33⁴ ≡ 4
- 43⁸ ≡ 2
- 53¹³ = 3⁸·3⁴·3
2 × 4 × 3 mod 7 = 3.
What must remain true (Loop Invariant)
Every transformation used by Modular arithmetic preserves the mathematical quantity or relation being computed.
Reference pseudocode
1modularArithmetic(input):
2 normalize input and define the mathematical state
3 while the state can be reduced:
4 apply one identity-preserving transformation
5 convert the reduced state into the requested result
6 return result
Verify your trace
- • Write the state after every step.
- • Confirm the invariant still holds.
- • Count visited states to derive complexity.
- • Repeat with an edge-case input.
Cost Model
Complexity & Trade-offs
OperationTimeSpaceWhy
Fast exponentiation
O(log exponent)
O(1) iterative
The bound follows from the number of states visited and the work performed per transition.When to use it
- Counting, divisibility, modular cycles, masks, and overflow-safe arithmetic.
- Replacing simulation with a mathematical identity.
- Encoding compact state for search and dynamic programming.
Common mistakes
- Using an identity without checking its domain or overflow behavior.
- Forgetting how the language handles negative remainder and signed shifts.
- Confusing value magnitude with the number of input values.
Practice prompts
- Reproduce the worked Modular arithmetic example without looking at the trace.
- Change one input condition and explain whether the Modular arithmetic invariant still holds.
- Implement the approach, derive its cost, and compare it with a straightforward baseline.
Mastery check
Can you derive it instead of memorizing it?
State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.