整除分块
整除分块
解决什么样的问题
在数论问题中,我们经常会遇到形如下面的求和式:
其中
整除分块(也叫做数论分块)就是用来快速计算这类求和式的算法,它可以将时间复杂度优化到
取值数量的上界
定理:对于正整数
:::info[证明]
我们将
第一部分:
第二部分:
此时有:
\left\lfloor \frac{n}{i} \right\rfloor < \frac{n}{\sqrt{n}} = \sqrt{n} 即
\lfloor \frac{n}{i} \rfloor 的取值是小于\sqrt{n} 的正整数,因此最多也只有\lfloor \sqrt{n} \rfloor 种不同取值(严格地说,小于\sqrt{n} 的正整数个数不超过\sqrt{n} )。
:::
算法原理
如果我们知道某一块的左端点是
换句话说:找到最大的
右端点公式:已知左端点
:::info[证明]
设
我们要找最大的
对右侧不等式变形:
对左侧不等式变形:
因此
因为
:::
:::success[代码]{open}
for (LL l = 1, r; l <= n; l = r + 1) {
r = n / (n / l);
// do sth.
}
:::
例题
约数个数和
题意:给定正整数
做法:
考虑枚举因数
使用整除分块,对于一个块
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
LL n, s;
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n;
for (LL l = 1, r; l <= n; l = r + 1) {
r = n / (n / l);
s += n / l * (r - l + 1);
}
cout << s;
return 0;
}
:::
P2424 约数和
利用前缀和,设
和上一题一样的套路,枚举因数
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
LL l, r;
LL C(LL n) {
LL s = 0;
for (LL l = 1, r; l <= n; l = r + 1) {
r = n / (n / l);
s += n / l * (l + r) * (r - l + 1) / 2;
}
return s;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> l >> r;
cout << C(r) - C(l - 1);
return 0;
}
:::
P2260 [清华集训 2012] 模积和
很有技巧性的一道整除分块题。
利用容斥,原式转化为
则
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int M = 19940417;
LL n, m;
LL C(LL n) {
LL s = n * n % M;
for (LL l = 1, r; l <= n; l = r + 1) {
r = n / (n / l);
s = (s - (l + r) * (r - l + 1) / 2 % M * (n / l) % M + M) % M;
}
return s;
}
LL V(__int128 n) {
return n * (n + 1) * (2 * n + 1) / 6 % M;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
LL s = min(n, m) * n % M * m % M;
for (LL l = 1, r; l <= min(n, m); l = r + 1) {
LL x = n / l, y = m / l;
r = min(n / x, m / y);
s = (s + x * y % M * (V(r) - V(l - 1) + M) % M - (x * m % M + y * n % M) % M * (((l + r) * (r - l + 1) / 2) % M) % M + M) % M;
}
cout << (C(n) * C(m) % M - s + M) % M;
return 0;
}
:::
CF830C Bamboo Partition
首先得到基础的公式
转化为向下取整
也就是
可以将这个式子视为一个
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int N = 105;
LL n, m, k, a[N], s;
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i], s += a[i], m = max(m, a[i]), a[i]--;
}
LL v = 0;
for (LL l = 1, r; l <= m + k; l = r + 1) {
r = 1e18;
LL c = 0;
for (int i = 1; i <= n; i++) {
a[i] >= l && (r = min(r, a[i] / (a[i] / l))), c += a[i] / l + 1;
}
LL d = min(r, (k + s) / c);
d >= l && (v = max(v, d));
}
cout << v;
return 0;
}
:::