Dynamic Programming21 sections · 916 units
Open in Course

Nim Game - Mathematical Insight

Beyond brute force

The DP reveals a pattern: you win if n≢0(mod4)n \not\equiv 0 \pmod 4. Can we prove this directly? From n0(mod4)n \equiv 0 \pmod 4: any move (1, 2, or 3) leaves n≢0(mod4)n' \not\equiv 0 \pmod 4. Opponent wins. From n≢0(mod4)n \not\equiv 0 \pmod 4: take nmod4n \mod 4 stones. Leave n0(mod4)n' \equiv 0 \pmod 4. Opponent loses.

This is the power of game theory DP: compute the pattern with DP, then prove and simplify to O(1)O(1). This pattern appears in many game theory problems. Look for cyclic structures in the win/lose sequence.