# 类欧几里得算法

对于求和式 $f(a,b,c,n)=\sum_{i=0}^n \lfloor \frac{ai+b}{c} \rfloor$

当 $a \geq c$ 或 $b \geq c$ 时，设 $a‘=a \; mod \; c$，$b‘=b \; mod \; c$，有

\begin{align*} f(a,b,c,n) = & \sum_{i=0}^n \; \lfloor \frac{ai+b}{c} \rfloor \\ = & \sum_{i=0}^n \; \lfloor \frac{a‘i+b‘}{c} \rfloor + \lfloor \frac{a}{c} \rfloor \times i + \lfloor \frac{b}{c} \rfloor \\ = & \; f(a‘,b‘,c,n) + \frac{n(n+1)}{2} \times \lfloor \frac{a}{c} \rfloor + (n+1) \times \lfloor \frac{b}{c} \rfloor \end{align*}

当 $a<c$ 且 $b<c$ 时，设 $m= \lfloor \frac{an+b}{c} \rfloor$，有

\begin{align*} f(a,b,c,n) = & \sum_{i=0}^n \; \lfloor \frac{ai+b}{c} \rfloor \\ = & \sum_{j=1}^m \sum_{i=0}^n \; [ \lfloor \frac{ai+b}{c} \rfloor \geq j ] \\ = & \sum_{j=0}^{m-1} \sum_{i=0}^n \; [ \lfloor \frac{ai+b}{c} \rfloor \geq j+1 ] \\ = & \sum_{j=0}^{m-1} \sum_{i=0}^n \; [ ai \geq jc+c-b ] \\ = & \sum_{j=0}^{m-1} \sum_{i=0}^n \; [ ai > jc+c-b-1 ] \\ = & \sum_{j=0}^{m-1} \sum_{i=0}^n \; [ i > \lfloor \frac{jc+c-b-1}{a} \rfloor ] \\ = & \sum_{j=0}^{m-1} n- \lfloor \frac{jc+c-b-1}{a} \rfloor \\ = & \; nm - \sum_{j=0}^{m-1} \; \lfloor \frac{jc+c-b-1}{a} \rfloor \\ = & \; nm-f(c,c-b-1,a,m-1) \end{align*}

这与欧几里得算法通过取模缩小范围的思想相似，时间复杂度为 $O(log \; a)$

ll f(ll a, ll b, ll c, ll n) {
if (!a) return b / c * (n + 1);
if (a < c && b < c) {
ll m = (a * n + b) / c;
if (!m) return 0;
return n * m - f(c, c - b - 1, a, m - 1);
}
if (n & 1)
return f(a % c, b % c, c, n) + (n + 1) / 2 * n * (a / c) + (n + 1) * (b / c);
return f(a % c, b % c, c, n) + n / 2 * (n + 1) * (a / c) + (n + 1) * (b / c);
}
View Code

(0)
(0)

© 2014 mamicode.com 版权所有 京ICP备13008772号-2