跳到正文

算法·理论

Nim 积学习笔记

r_syh0213约 6 分钟
原文
文章信息与版本

文章信息

发布
2026年9月1日
收录
2026年9月1日
更新
2026年9月2日
篇幅
约 6 分钟
获赞
1

版本

  1. v3当前
  2. v2
  3. v1

太难了!!!

定义

两数 x,yx,y 的 Nim 积定义为:

x⊗y=mex⁡{(x⊗j)⊕(y⊗i)⊕(i⊗j)∣0≤i<x,0≤j<y}x \otimes y = \operatorname{mex}\{ (x \otimes j) \oplus (y \otimes i) \oplus (i \otimes j) \mid 0 \le i < x,0 \le j < y \}

⊗\otimes 为 Nim 积,⊕\oplus 为异或。

打表

⊗\otimes012345678910
000000000000
1012345678910
20231810119121415
3031212151314475
40481262141011153
505101527813369
6061113148537112
7079141013341586
8081241137151351
9091471561851211
100101553912611114

性质

证明等我学会了再补 (可能这辈子都学不会)。

运算性质

由表可以看出来,x⊗0=0,x⊗1=xx \otimes 0 = 0,x \otimes 1 = x。

Nim 积和异或运算满足交换律和结合律,即:

x⊗y=y⊗xx⊗(y⊗z)=(x⊗y)⊗zx⊗(y⊕z)=(x⊗y)⊕(x⊗z)\begin{aligned} x \otimes y &= y \otimes x \\ x \otimes (y \otimes z) &= (x \otimes y) \otimes z \\ x \otimes (y \oplus z) &= (x \otimes y) \oplus (x \otimes z) \end{aligned}

有关费马数的性质

经过数学家的艰苦卓绝的努力,我们有两个十分强大的运算法则。

定义 Fermat 2-power x=22nx = 2^{2^n},其中 n∈Nn \in \mathbb{N}。

  1. 一个 Fermat 2-power 与任意小于它的数的 Nim 积为一般意义下乘法的积,x⊗y=x(x>y)x \otimes y = x (x>y)。
  2. 一个 Fermat 2-power 与自己的 Nim 积为自己的 32\frac{3}{2} 倍,x⊗x=x⊕x2=32xx \otimes x = x \oplus \frac{x}{2} = \frac{3}{2} x。

求 Nim 积

暴力求是 O(x2y2)O(x^2 y^2) 的,利用一些性质能做到 O(log⁡xlog⁡y)O(\log x \log y)。

定义 f(x,y)=x⊗yf(x,y) = x \otimes y。
x∨y=0/1x \lor y = 0/1 的情况直接判掉。

定义 g(x,y)=2x⊗2yg(x,y)= 2^x \otimes 2^y,所以 f(x,y)=⨂x′∈x,y′∈yg(x′,y′)f(x,y) = \bigotimes_{x' \in x,y' \in y} g(x',y')。
接下来求 g(x,y)g(x,y)。考虑拆位,变成一个个 Fermat 2-power 。

2x⊗2y=(⨂x′∈x22x′)⊗(⨂y′∈y22y′)2^x \otimes 2^y = \left( \bigotimes_{x' \in x} 2^{2^{x'}} \right) \otimes \left( \bigotimes_{y' \in y} 2^{2^{y'}} \right)

从高到低 依次考虑 x,yx,y 的每一位,如果这位都为 00 显然可以跳过。

若两个都为 11,对于这一位 2t2^t,设 W=22t,A=2x−2t,B=2y−2tW = 2^{2^t},A = 2^{x - 2^t},B=2^{y - 2^t},有 A,B<WA,B <W。
答案就是 (W⊗A)⊗(W⊗B)(W \otimes A) \otimes (W \otimes B),化简成 32W⊗(A⊗B)\frac{3}{2} W \otimes (A \otimes B)。
接下来将 2x,2y2^x,2^y 去掉最高位的 tt,变成 A,BA,B,继续向低位递归。

若只有一个 11,不妨设 xx 此位为 11。
同理,对于这一位 2t2^t,设 W=22t,A=2x−2t,B=2yW = 2^{2^t},A = 2^{x - 2^t},B=2^y。
答案是 (W⊗A)⊗B=W⊗(A⊗B)(W \otimes A) \otimes B=W \otimes (A \otimes B),将 2x2^x 的最高位 tt 去掉,继续递归。

显然可以利用交换律把两种情况分开:

2x⊗2y=(⨂i∈{x⊕y}22i)⊗(⨂i∈{x∧y}32×22i)=(∏i∈{x⊕y}22i)⊗(⨂i∈{x∧y}32×22i)\begin{aligned} &2^x \otimes 2^y \\ =& \left( \bigotimes_{i \in \{ x \oplus y \}} 2^{2^i} \right) \otimes \left( \bigotimes_{i \in \{ x \land y \}} \frac{3}{2} \times 2^{2^i} \right) \\ =& \left( \prod_{i \in \{ x \oplus y \}} 2^{2^i} \right) \otimes \left( \bigotimes_{i \in \{ x \land y \}} \frac{3}{2} \times 2^{2^i} \right) \end{aligned}

对于前者可以直接算,后者可以递归计算。
因为递归只会遍历两个所有二进制位,所以单次复杂度为 O(log⁡xlog⁡y)O(\log x\log y)。

代码先咕咕咕了

前方为待施工区域,下次再来吧…

原文
存档评论2 条抓取于