Problem. A pile of stones; players alternately take stones; whoever takes the last stone wins. (The “21 game” is , in reverse form.)
Answer: the first player loses iff ; the winning move is to take stones.
bool bachetFirstWins(long long n, long long k) { return n % (k + 1) != 0; } // take 1..k, last stone wins| Variant | Losing positions |
|---|---|
| misère (taking the last stone loses) | |
| allowed moves form a set | compute win/lose by DP; the pattern is eventually periodic |
| several piles | Grundy value per pile, XOR them (Sprague–Grundy) |
Proof: multiples of k + 1 lose
From a multiple of , any move takes stones and leaves a non-multiple. From a non-multiple, taking stones leaves a multiple. Position is a loss for the player to move. By induction, multiples of are losing and all others winning. Checked against the game DP for , .