整数裂项
中考前一周隔壁班同学拿此题问我( m = 98 , n = 3 m = 98, n = 3 m=98,n=3)。我当场用平方求和立方求和完成。他们后面查到比较正常的裂项相消方法,现给出一般情况的题目及答案,见下:
已知整数 2 ≤ m , n ≤ 1 0 6 2 \le m, n \le10^6 2≤m,n≤106,多组询问,计算:
∑ a = 1 m ∏ b = 0 n − 1 ( a + b ) \sum_{a=1}^m \prod_{b=0}^{n-1} (a+b) a=1∑mb=0∏n−1(a+b)
通俗来讲,就是求:
1 × 2 × ⋯ × n + 2 × 3 × ⋯ × ( n + 1 ) + ⋯ + m × ( m + 1 ) × ⋯ × ( m + n − 1 ) 1 \times 2 \times \cdots \times n + 2 \times 3 \times \cdots \times (n+1) + \cdots + m \times (m+1) \times \cdots \times (m+n - 1) 1×2×⋯×n+2×3×⋯×(n+1)+⋯+m×(m+1)×⋯×(m+n−1)
解:
∑ a = 1 m ∏ b = 0 n − 1 ( a + b ) = ∑ a = 1 m [ ( a + n ) − ( a − 1 ) ] n + 1 ⋅ ∏ b = 0 n − 1 ( a + b ) = 1 n + 1 ∑ a = 1 m [ ∏ b = 0 n ( a + b ) − ∏ b = − 1 n − 1 ( a + b ) ] = 1 n + 1 [ ∑ a = 1 m ∏ b = 0 n ( a + b ) − ∑ a = 1 m ∏ b = − 1 n − 1 ( a + b ) ] = 1 n + 1 [ ∑ a = 1 m ∏ b = 0 n ( a + b ) − ∑ a = 0 m − 1 ∏ b = 0 n ( a + b ) ] = 1 n + 1 ∏ b = 0 n ( m + b ) = ( m + n ) ! ( m − 1 ) ! ( n + 1 ) \begin{aligned} &\sum_{a=1}^m \prod_{b=0}^{n-1} (a+b)\\ =&\sum_{a=1}^m \frac{[(a+n)-(a-1)]}{n+1} \cdot \prod_{b=0}^{n-1} (a+b)\\ =&\frac{1}{n+1}\sum_{a=1}^m\left[{\prod_{b=0}^n(a+b) - \prod_{b=-1}^{n-1}(a+b)} \right]\\ =&\frac{1}{n+1}\left[{\sum_{a=1}^m\prod_{b=0}^n(a+b) - \sum_{a=1}^m\prod_{b=-1}^{n-1}(a+b)}\right]\\ =&\frac{1}{n+1}\left[{\sum_{a=1}^m\prod_{b=0}^n(a+b) - \sum_{a=0}^{m-1}\prod_{b=0}^n(a+b)}\right]\\ =&\frac{1}{n+1}\prod_{b=0}^n(m+b)\\ =&\frac{(m+n)!}{(m-1)!(n+1)} \end{aligned} ======a=1∑mb=0∏n−1(a+b)a=1∑mn+1[(a+n)−(a−1)]⋅b=0∏n−1(a+b)n+11a=1∑m[b=0∏n(a+b)−b=−1∏n−1(a+b)]n+11[a=1∑mb=0∏n(a+b)−a=1∑mb=−1∏n−1(a+b)]n+11[a=1∑mb=0∏n(a+b)−a=0∑m−1b=0∏n(a+b)]n+11b=0∏n(m+b)(m−1)!(n+1)(m+n)!
若求上述式子对一个大质数(如 998244353 998244353 998244353)取模的值,则可以:
O ( n ) O(n) O(n) 预处理阶乘取模、逆元、阶乘逆元, O ( 1 ) O(1) O(1) 查询。
补充知识点:
递推求逆元:
p ≡ 0 a ⋅ ⌊ p / a ⌋ + r ≡ 0 a ⋅ a − 1 ⋅ r − 1 ⋅ ⌊ p / a ⌋ + r ⋅ a − 1 ⋅ r − 1 ≡ 0 r − 1 ⋅ ⌊ p / a ⌋ + a − 1 ≡ 0 a − 1 ≡ − r − 1 ⋅ ⌊ p / a ⌋ a − 1 ≡ r − 1 ⋅ ( p − ⌊ p / a ⌋ ) ( m o d p ) \begin{aligned} p &\equiv 0\\ a \cdot \lfloor p / a \rfloor + r&\equiv 0\\ a\cdot a^{-1} \cdot r^{-1} \cdot \lfloor p / a \rfloor + r\cdot a^{-1} \cdot r^{-1} &\equiv 0\\ r^{-1} \cdot \lfloor p / a \rfloor + a^{-1} &\equiv 0\\ a^{-1} &\equiv -r^{-1} \cdot \lfloor p / a \rfloor\\ a^{-1} &\equiv r^{-1} \cdot (p- \lfloor p / a \rfloor) \pmod p \end{aligned} pa⋅⌊p/a⌋+ra⋅a−1⋅r−1⋅⌊p/a⌋+r⋅a−1⋅r−1r−1⋅⌊p/a⌋+a−1a−1a−1≡0≡0≡0≡0≡−r−1⋅⌊p/a⌋≡r−1⋅(p−⌊p/a⌋)(modp)
inv[a] = inv[p % a] * (p-p/a);