(本文用 绿 色 \color{green}绿色 绿色标注一切函数,用 紫 色 \color{purple}紫色 紫色标注部分可以 O ( 1 ) O(1) O(1)计算的常量式,便于观察)(不知道为什么加了颜色过后括号不能自动变大了,将就看吧= =)
概述
类欧几里得算法用于求形如 f ( a , b , c , n ) = ∑ i = 0 n ⌊ a i + b c ⌋ \color{green}{f(a, b, c, n)} \color{o} = \sum \limits_{i = 0}^{n} \left\lfloor \frac{a i + b}{c} \right\rfloor f(a,b,c,n)=i=0∑n⌊cai+b⌋的式子。这个式子有个几何意义,表示求下图中阴影部分中的整点个数(直线为 y = a x + b y=ax+b y=ax+b):
算法
令 a ′ = a % c , b ′ = b % c a' = a \% c, b' = b \% c a′=a%c,b′=b%c,由定义式得 f ( a , b , c , n ) = ∑ i = 0 n ( ⌊ a ′ i + b ′ c ⌋ + ⌊ a c ⌋ i + ⌊ b c ⌋ ) = f ( a ′ , b ′ , c , n ) + ⌊ a c ⌋ ∑ i = 0 n i + ( n + 1 ) ⌊ b c ⌋ \begin{aligned} \color{green}{f(a, b, c, n)} \color{o} &= \sum_{i = 0}^{n} \left( \left\lfloor \frac{a' i + b'}{c} \right\rfloor + \left\lfloor \frac{a}{c} \right\rfloor i + \left\lfloor \frac{b}{c} \right\rfloor \right) \\ &= \color{green} f(a', b', c, n) \color{o} + \color{purple} \left\lfloor \frac{a}{c} \right\rfloor \sum_{i = 0}^{n} i \color{o} + \color{purple} (n + 1) \left\lfloor \frac{b}{c} \right\rfloor \end{aligned} f(a,b,c,n)=i=0∑n(⌊ca′i+b′⌋+⌊ca⌋i+⌊cb⌋)=f(a′,b′,c,n)+⌊ca⌋i=0∑ni+(n+1)⌊cb⌋于是只需要处理 a , b < c a, b < c a,b<c的情况。
设 m = ⌊ a n + b c ⌋ m = \left\lfloor \frac{a n + b}{c} \right\rfloor m=⌊can+b⌋,则 f ( a , b , c , n ) = ∑ i = 0 n ∑ j = 0 m [ j ≤ ⌊ a i + b c ⌋ ] = ∑ i = 0 n ∑ j = 0 m − 1 [ j < ⌊ a i + b c ⌋ ] = ∑ j = 0 m − 1 ∑ i = 0 n [ j < ⌊ a i + b c ⌋ ] \begin{aligned} \color{green}{f(a, b, c, n)} \color{o} &= \sum_{i = 0}^{n} \sum_{j = 0}^{m} \left[ j \leq \left\lfloor \frac{a i + b}{c} \right\rfloor \right] \\ &= \sum_{i = 0}^{n} \sum_{j = 0}^{m - 1} \left[ j < \left\lfloor \frac{a i + b}{c} \right\rfloor \right] \\ &= \sum_{j = 0}^{m - 1} \sum_{i = 0}^{n} \left[ j < \left\lfloor \frac{a i + b}{c} \right\rfloor \right] \end{aligned} f(a,b,c,n)=i=0∑nj=0∑m[j≤⌊cai+b⌋]=i=0∑nj=0∑m−1[j<⌊cai+b⌋]=j=0∑m−1i=0∑n[j<⌊cai+b⌋]
现在要想办法把里面变成 i i i为主元。
如下图所示,可以看出 0 ≤ j < 5 0 \leq j < 5 0≤j<5,结合图示可以得到 j < ⌊ a i + b c ⌋ ⇔ ( j + 1 ) c ≤ a i + b j < \left\lfloor \frac{a i + b}{c} \right\rfloor \Leftrightarrow (j + 1) c \leq a i + b j<⌊cai+b⌋⇔(j+1)c≤ai+b
即 ( j + 1 ) c < a i + b + 1 (j + 1) c < a i + b + 1 (j+1)c<ai+b+1,即 i > ⌊ c j − b + c − 1 a ⌋ i > \left\lfloor \frac{c j - b + c - 1}{a} \right\rfloor i>⌊acj−b+c−1⌋于是可以继续化简了 f ( a , b , c , n ) = ∑ j = 0 m − 1 ∑ i = 0 n [ i > ⌊ c j − b + c − 1 a ⌋ ] = ∑ j = 0 m − 1 ( n − ⌊ c j − b + c − 1 a ⌋ ) = m n − ∑ j = 0 m − 1 ⌊ c j − b + c − 1 a ⌋ = m n − f ( c , c − b − 1 , a , m − 1 ) \begin{aligned} \color{green}{f(a, b, c, n)} \color{o} &= \sum_{j = 0}^{m - 1} \sum_{i = 0}^{n} \left[ i > \left\lfloor \frac{c j - b + c - 1}{a} \right\rfloor \right] \\ &= \sum_{j = 0}^{m - 1} \left( n - \left\lfloor \frac{c j - b + c - 1}{a} \right\rfloor\right) \\ &= \color{purple}{m n} \color{o} - \sum_{j = 0}^{m - 1} \left\lfloor \frac{c j - b + c - 1}{a} \right\rfloor \\ &= \color{purple}{m n} \color{o} - \color{green}{
{}f(c, c - b - 1, a, m - 1)} \end{aligned} f(a,b,c,n)=j=0∑m−1i=0∑n[i>⌊a