一句话概括

Nim(尼姆游戏)是组合博弈论中最基础也最重要的模型。它的完整解法由 Charles L. Bouton 于 1901 年给出:把所有堆的石子数按位异或(XOR),结果为零则先手必败,非零则先手必胜。 这个”异或和为零”的判据,后来成为整个无偏博弈(impartial game)理论——Sprague–Grundy 定理——的起点。


Part I · English

1. Definition and rules

Nim is played with several piles (heaps) of objects. Two players alternate moves. On each turn a player must:

  1. choose exactly one pile, and
  2. remove at least one object from it (possibly the entire pile).

The player who takes the last object wins (this is called normal play).

Formally, a position is a multiset of non-negative integers; a move replaces some by any smaller value . A player unable to move loses.

Why the order of piles does not matter

Because a move acts on one pile and piles are independent, a position is fully described by the multiset of pile sizes. Write and — they are the same position.

Terminology / 术语对照

English中文Meaning
impartial game无偏博弈 / 公正博弈Both players have the same available moves
normal play正常规则 / 通常规则Player taking the last object wins
misère play反规则 / 变态规则Player taking the last object loses
P-position必败态(后手必胜)Player to move loses with best play
N-position必胜态(先手必胜)Player to move wins with best play
nim-sum尼姆和 / 异或和Bitwise XOR of all pile sizes
Grundy numberGrundy 数 / SG 值The nim-value of a game component
mex最小排斥值Minimum excludant: smallest non-negative integer not in a set

2. The core tool: nim-sum

The nim-sum of a position is

where is bitwise XOR (exclusive or). Recall:

  • for every
  • XOR is associative and commutative

These three facts are used constantly: XOR-ing the same number twice cancels it out. In particular, a move always changes the nim-sum, because replacing by changes by .

How to compute a nim-sum by hand

Write the piles in binary and XOR column by column — in each bit position the result is 1 exactly when an odd number of piles have a 1 there.

Example:

pile421
3011
4100
5101
XOR010

The nim-sum is , so is an N-position — the player to move wins.

3. Bouton’s theorem

Theorem (Bouton, 1901)

A Nim position is a P-position (the player to move loses) if and only if its nim-sum is .

The proof is short and worth knowing, because the same two-step pattern proves almost every impartial-game result.

Step 1 — from nim-sum , every move leaves nim-sum . Suppose and we replace by . The new nim-sum is and implies . So . ✔

Step 2 — from nim-sum , there is always a move to nim-sum . Let be the highest set bit of . Since , some pile has a in that bit (an odd number of piles do). Define

Then (the highest differing bit is exactly bit , where has 1 and has 0), so this is a legal move. And

so the new nim-sum is . ✔

Conclusion. From a position every move hands the opponent a non-zero position; from a non-zero position you can always hand back a position. Since the all-zero position (nim-sum ) is a loss for the player to move, the zero positions are exactly the losing ones. ✔

How to find the winning move in practice

  1. Compute .
  2. Take = the highest set bit of .
  3. Choose any pile whose value has bit set, and replace it with . This is the only method you ever need.

A neat consequence: the number of winning moves is always odd

Step 2 above says a pile can be improved exactly when its bit is set. Since bit of is 1, an odd number of piles have bit set — and for each of them is a legal winning move. So in any N-position the count of winning moves is odd (never 0, never 2). Check it: has 3, has 3, while , and each have exactly 1.

Worked example:

. The highest set bit of is bit (value 2). Which piles have bit 2 set? Only . So we must modify the -pile:

The unique winning move is , giving , and indeed . Every other move leaves a non-zero nim-sum, i.e. a winning position for the opponent.

Common mistake

Reducing the largest pile is not a strategy. In the intuitive move “5 → 2” gives with nim-sum — a losing move. Always compute the nim-sum; never eyeball the biggest pile.

Small losing positions (P-positions)

All positions with nim-sum . In particular:

  • Two piles: — equal piles lose.
  • Three piles with sizes in , exactly these seven: , , , , , , .
  • More generally: any position that splits into equal pairs, plus , , , , etc.

4. Misère Nim: last to move loses

Now the player who takes the last object loses. Almost nothing changes:

Theorem (misère Nim)

If every non-empty pile has size 1, the player to move wins iff the number of such piles is even. Otherwise (at least one pile of size ), the normal-play rule still applies: the player to move wins iff the nim-sum is non-zero.

The intuition: misère play only differs from normal play in the endgame, when nothing is left but single objects. As long as a pile of size remains, a player always has a “spare” move available to control the parity, so the normal-play strategy remains optimal.

Examples. — mover wins. — mover loses. — at least one pile , nim-sum , mover wins. — nim-sum , mover loses. — nim-sum , mover loses. — all piles are 1, one pile, odd, mover loses.

5. Beyond Nim: the Sprague–Grundy theorem

Bouton’s theorem is the base case of a much larger structure.

Sprague–Grundy theorem

Every impartial game under normal play is equivalent to a single Nim pile. Define the Grundy number (nim-value) of a position by with . Then a position is a loss for the mover iff . Moreover the disjunctive sum (play in any one component) has Grundy number So the XOR rule is not special to Nim — it is the universal law for sums of impartial games.

A Nim pile of size has , which is exactly why Bouton’s nim-sum works.

Tiny worked example. Consider the subtraction game “take 1 or 2 objects from a single pile; last to take wins”. Then , , , , . So the pattern is : the mover loses exactly when .

6. Important variants

Single-pile subtraction (“counting game”). One pile of ; take to objects; last to take wins. The mover wins iff . For this is the classic n mod 4 ≠ 0 result (the LeetCode 292 “Nim Game” problem). Note that this is a single-pile subtraction game, not mathematical Nim — the name is misleading; there is no XOR involved. (Its misère version, where the last taker loses, flips to: mover loses iff , i.e. for .)

Wythoff’s game. Two piles; a move removes any positive number from one pile, or the same positive number from both. The losing positions are for — giving (the cold positions / P-positions).

Moore’s Nim. With piles you may remove from at most piles. A position is a P-position iff for every binary bit position, the sum of the bits of all pile sizes at that position is divisible by :

This is not the XOR rule

Only the case coincides with Bouton’s nim-sum (then , so “every column has an even number of 1s” is exactly “XOR = 0”). For the bit-sum is genuinely different from XOR. Example with (so mod 3): has XOR but bit-column sums — not divisible by 3, so the mover wins; while has XOR but column sum — so the mover loses.

Moore’s “at most ” vs “exactly “. Moore’s game (at most piles) is solved by the rule above and is polynomial-time solvable. The superficially similar game where you must take from exactly piles (Exact -Nim) is a different and much harder problem with its own research literature — do not conflate the two.

All piles of size 1. Covered by the misère rule above; in normal play it is just the XOR rule, i.e. mover wins iff the number of piles is odd.

7. Complexity and where it is used

  • Computing the nim-sum takes time linear in the number of piles, , using extra space; finding the winning move is a second linear pass. Nim is therefore in P — tractable, in fact trivial.
  • This is in sharp contrast to general impartial games: deciding the winner of Generalized Geography is PSPACE-complete (Schaefer 1978; Lichtenstein–Sipser 1980). Note carefully — it is not true that “all impartial games are hard”: Nim is a polynomial-time counterexample. A subtle bonus fact: for Undirected Geography the winner can be determined in polynomial time, yet computing its Grundy value is PSPACE-complete.
  • Where it shows up:
    • Algorithmic contests. Nim and its variants are standard problems (e.g. Luogu P2197, AtCoder ABC 255 G “Constrained Nim”, the cp-algorithms chapter).
    • Combinatorial game theory. Grundy values power the analysis of Go endgames, octal games, and the theory in Winning Ways.
    • Foundational mathematics. Nim is the canonical cold game; Conway’s theory of surreal numbers builds on such games.
    • Model thinking. The P/N alternation is the prototype of “invariant + induction” reasoning that recurs throughout algorithm design: find a quantity (here the nim-sum) that the opponent cannot restore.

8. Exercises

Work them out before opening the answers.

9. References

  • C. L. Bouton, “Nim, a game with a complete mathematical theory”, Annals of Mathematics, 2nd series, 3(1/4), 1901–1902, pp. 35–39. — JSTOR 1967631. (The page range is the near-universal citation; the primary record is behind an access wall, so treat it as high-confidence but not directly confirmed.)
  • R. P. Sprague, “Über mathematische Kampfspiele”, Tôhoku Math. J. 41, 1935/36, pp. 438–444; P. M. Grundy, “Mathematics and games”, Eureka 2, 1939, pp. 6–8. (Sources differ on whether Sprague’s paper is dated 1935 or 1936; “1935/36” is the safest form.)
  • W. A. Wythoff, “A modification of the game of nim”, Nieuw Archief voor Wiskunde 7(2), 1907, pp. 199–202.
  • E. H. Moore, “A generalization of the game called Nim”, Annals of Mathematics, 2nd series, 11(3), 1910, pp. 93–94.
  • Wikipedia, Nim — Bouton’s theorem, misère play, variants.
  • Wikipedia, Sprague–Grundy theorem
  • Wikipedia, Wythoff’s game
  • cp-algorithms, Sprague-Grundy theorem. Nim
  • J. H. Conway, On Numbers and Games, 2nd ed., A K Peters, 2001.
  • E. R. Berlekamp, J. H. Conway, R. K. Guy, Winning Ways for Your Mathematical Plays, 2nd ed., A K Peters, 2001.
  • OEIS A000201 and A001950 — the Beatty sequences and behind Wythoff’s cold positions.

Part II · 中文

1. 定义与规则

Nim(尼姆游戏) 由若干堆(heap / pile)物件组成,两人轮流行动。每一步必须:

  1. 选择恰好一堆;
  2. 从中取走至少一个物件(可以整堆取走)。

取走最后一个物件的人获胜——这称为正常规则(normal play)。

形式化地:一个局面是一个非负整数多重集 ,一步行动把某个 换成更小的 ;无路可走者输。

为什么堆的顺序无关紧要

因为一步只作用在一堆上,且各堆互相独立,所以局面完全由”各堆大小的多重集”决定。 与 是同一个局面。

2. 核心工具:异或和(nim-sum)

局面 的 nim-sum 为

其中 是按位异或(XOR)。三条要用一辈子的性质:

  • (同一个数异或两次会抵消)
  • 异或满足结合律与交换律

由第一条立刻得到:任何一步都会改变 nim-sum。因为把 换成 , 的变化量是 。

手算 nim-sum

把各堆写成二进制,按位列对齐后逐列异或:某一列上 1 的个数为奇数,结果的这一位就是 1。

例:

堆421
3011
4100
5101
异或010

nim-sum ,所以 是必胜态,轮到谁走谁赢。

3. Bouton 定理

定理(Bouton, 1901)

Nim 局面是必败态(轮走者必败)当且仅当其 nim-sum 为 。

证明只有两步,而且这个”两步模式”几乎可以用来证明所有无偏博弈的结论。

第一步:nim-sum 为 时,任何一步都会让它变成非 。 设 ,把 换成 ,则新 nim-sum 为 因 ,故 ,即 。✔

第二步:nim-sum 非 时,一定存在一步把它变回 。 设 为 的最高有效位。由于 ,必存在某堆 在第 位上为 1(因为该位上 1 的总数为奇数)。令

则 (两者最高不同的位正是第 位: 为 1、 为 0),所以这是合法走法。并且

新 nim-sum 为 。✔

结论。 从 局面出发,任何走法都把非 局面交给对手;从非 局面出发,总能交回一个 局面。而全零局面(nim-sum 为 )是轮走者必败,所以nim-sum 为 的局面恰好就是必败态。✔

实战中怎么找制胜一步

  1. 先算 ;
  2. 取 的最高有效位 ;
  3. 找一堆在第 位上是 1 的,把它改成 。 这三步就是全部方法。

一个漂亮的推论:制胜一步的个数永远是奇数

上面第 2 步说明,“能被改进”的堆恰好是第 位为 1 的那些堆。由于 的第 位是 1,第 位为 1 的堆有奇数个,其中每一个都能通过 走出合法制胜一步。所以任何必胜态里,制胜一步的个数都是奇数(不可能是 0,也不可能是 2)。可以验证: 有 3 个, 有 3 个;而 、、 都恰好只有 1 个。

例题:

。 的最高有效位是第 2 位(值为 2)。哪些堆的第 2 位是 1?只有 。所以必须改动 3 这一堆:

唯一的制胜一步是 ,得到 ,而 。其它任何走法都会留下非 的 nim-sum,也就是把必胜局面送给对手。

常见错误

“取最大那堆”不是策略。在 中,凭直觉走""会得到 ,其 nim-sum 为 ——这是一步败着。永远老实算 nim-sum,不要目测最大堆。

小规模必败态(P-position)

所有 nim-sum 为 的局面。例如:

  • 两堆:——两堆相等时必败。
  • 三堆(各堆大小在 之间)恰好是这 7 个:、、、、、、。
  • 更一般地:任何”成对出现且每对相等”的局面,以及 、、、 等。

4. 反规则 Nim(misère):取最后一个者输

现在改成取走最后一个物件的人输。结论几乎不变:

定理(反规则 Nim)

若所有非空堆的大小都为 1,则轮走者必胜当且仅当堆数为偶数。 否则(至少存在一堆大小 ),正常规则仍然适用:轮走者必胜当且仅当 nim-sum 非 。

直觉:反规则与正常规则的差别只出现在残局——当场上只剩单个物件的时候。只要还存在一堆大小 ,玩家手里始终有”调节步数奇偶”的余量,因此正常规则的策略依然最优。

例子。 轮走者胜; 轮走者败; 存在 的堆,nim-sum ,轮走者胜; nim-sum ,轮走者败; nim-sum ,轮走者败; 全为 1、共 1 堆为奇数,轮走者败。

5. 从 Nim 到 Sprague–Grundy 定理

Bouton 定理只是一个更大结构的起点。

Sprague–Grundy 定理

正常规则下的每个无偏博弈都等价于一堆 Nim。定义局面 的 Grundy 数(nim-value): 并约定无路可走的局面 。则轮走者必败当且仅当 。 更重要的是,不相交博弈之和(每次只在一个子游戏里行动)满足 所以异或规则并不是 Nim 特有的——它是”无偏博弈之和”的普遍规律。

一堆大小为 的 Nim 的 Grundy 数恰好是 ,这正是 Bouton 的 nim-sum 有效的根本原因。

小例子。 考虑”单堆、每次取 1 或 2 个、取最后一个者胜”的取子游戏:,,,,。于是序列是 :轮走者在 时必败。

6. 重要变体

单堆取子(counting game)。 一堆 个,每次取 个,取最后一个者胜。轮走者必胜当且仅当 。取 就是经典的 结论(即 LeetCode 292 “Nim Game”)。注意:这是单堆减法游戏,不是数学意义上的 Nim——名字具有误导性,其中根本没有异或。(它的反规则版本——取最后一个者输——则反转为:轮走者必败当且仅当 , 时为 。)

Wythoff 游戏。 两堆,一步可以:从其中一堆取走任意正数,或从两堆各取走相同的正数。必败态(cold positions)为 取 得到

Moore 的 Nim。 共 堆,一次最多可从 堆中取子。该局面是必败态当且仅当:对每一个二进制位,所有堆在该位上的 1 的个数之和能被 整除:

这 不是异或规则

只有 时才与 Bouton 的 nim-sum 重合(此时 ,“每列 1 的个数为偶数”正好等价于”异或为 0”)。当 时,位和与异或本质不同。以 (模 3)为例: 的异或为 ,但各列 1 的个数是 ,不能被 3 整除,所以轮走者胜;而 的异或为 ,但某列 1 的个数是 ,所以轮走者败。

Moore 的”至多 堆”与”恰好 堆”。 Moore 游戏(至多 堆)由上规则完全解决,是多项式时间可解的。而表面上相似的”必须从恰好 堆中取子”(Exact -Nim)是另一个困难得多的问题,有独立的研究文献——不要把两者混为一谈。

全是大小为 1 的堆。 见上面的反规则;在正常规则下就是异或规则,即堆数为奇数时轮走者胜。

7. 复杂度与实际用途

  • 计算 nim-sum 只需 时间、 额外空间;再扫一遍即可找到制胜一步。所以 Nim 属于 P,不仅可解,而且是平凡的。
  • 这与一般无偏博弈形成鲜明对比:判断 Generalized Geography 的胜负是 PSPACE-complete 的(Schaefer 1978;Lichtenstein–Sipser 1980)。请注意——“所有无偏博弈都很难”是错的,Nim 就是多项式时间的反例。还有一个微妙的事实:无向 Geography 的胜负可以在多项式时间内判定,但计算它的 Grundy 数却是 PSPACE-complete 的。
  • 它出现在哪里:
    • 算法竞赛。 Nim 及其变体是标准题型(如洛谷 P2197、AtCoder ABC 255 G “Constrained Nim”,以及 cp-algorithms 的专章)。
    • 组合博弈论。 Grundy 数支撑着围棋官子、octal games 以及《Winning Ways》中的整套理论。
    • 基础数学。 Nim 是”冷博弈”(cold game)的典范,Conway 的超现实数理论正建立在此类博弈之上。
    • 思维模型。 P/N 态的交替是”不变量 + 归纳”这一推理范式的原型——先找一个对手无法复原的量(这里就是 nim-sum)。这种思路在算法设计中反复出现。

8. 实战检验题

请先自己做一遍,再展开答案核对。

9. 参考文献

  • C. L. Bouton, “Nim, a game with a complete mathematical theory”, Annals of Mathematics, 第二辑 3(1/4), 1901–1902, pp. 35–39. — JSTOR
  • Wikipedia, Nim(含 Bouton 定理、反规则与各变体)
  • Wikipedia, Sprague–Grundy theorem
  • Wikipedia, Wythoff’s game
  • cp-algorithms, Sprague-Grundy / Nim
  • J. H. Conway, On Numbers and Games, 2nd ed., A K Peters, 2001.
  • E. R. Berlekamp, J. H. Conway, R. K. Guy, Winning Ways for Your Mathematical Plays, 2nd ed., A K Peters, 2001.

附:延伸阅读(可选)

关于"要不要写代码"

本页刻意不使用程序代码——Nim 的价值在于定理与不变量本身。若日后想动手实现,核心只需三行逻辑:求异或和、找最高有效位、把对应堆改为 a[k] ^ S。相关在线练习可参考 LeetCode 292. Nim Game(单堆取 1–3 个的变体)。