杜教筛第一题!
但是我根本就没用杜教筛,我连杜教筛是什么都不知道。
但是首先我们知道一个结论:
∑i=1n∑d|ifd=∑i=1n∑d=1⌊ni⌋fd
左右的i意义不同。右边的
收缩变换的意义在于把枚举因数转换为枚举前缀。
然后我们看到∑d|nfd=n2−3n+2,套一个前缀和就变成了
∑i=1n∑d|ifd=∑i=1ni2−3i+2
右边的你肯定会吧,平方和一下就变成多项式了。
左边的用一个收缩变换,变成:
∑i=1n∑d=1⌊ni⌋fd=n3−3n2+2n3
“套一个前缀和”这个技巧叫做构造收缩变换,在求前缀时非常有用。
令S是
i=1的时候就能算出Sn了。于是我们把i=1的情况分开,再移一下项,就得到了最后的式子。注意右边i从2开始。
然后就套用一般的做法,先O(n2/3)预处理前n2/3的S,后面就递归求,用一个map来实现记忆化。
实现再稍微讲一下。你可以在草稿纸上写出一些
递归的部分,要用
#include<cstdio>
#include<map>
using namespace std;
const long long _mod = 1000000007;
map<int,int> m;
long long ans[1111111]; //前n^(2/3)的S
long long read() {
long long a = 0, c = getchar(), w = 1;
for(; c < '0' || c > '9'; c = getchar()) if(c == '-') w = -1;
for(; c >= '0' && c <= '9'; c = getchar()) a = a * 10 + c - '0';
return a * w;
}
long long exgcd(long long a, long long b, long long& d, long long& x, long long& y) {
if(!b) {d = a; x = 1; y = 0;}
else {exgcd(b, a%b, d, y, x); y -= x*(a/b);}
}
long long inv(long long a, long long n) {
long long d, x, y;
exgcd(a, n, d, x, y);
return (x+n)%n;
}
long long calc(long long x) {
if(x <= 1111111) return ans[x];
if(m[x] > 0) return m[x]; //记忆化
long long ans = x * x % _mod * x % _mod * inv(3, _mod) % _mod - x * x % _mod;
ans %= _mod;
if(ans < 0) ans += _mod;
ans += x * 2 % _mod * inv(3, _mod) % _mod;
ans %= _mod;
int bl; //bl是右端点
for(int i = 2; i <= x; i = bl + 1) {
bl = x / (x/i); //先更新bl
ans -= (bl-i+1) * calc(x/i) % _mod; //i是左端点
ans %= _mod;
if(ans < 0) ans += _mod;
}
m[x] = ans;
return ans;
}
int main() {
for(int i=1;i<1111111;i++)ans[i]=1ll*(i-1)*(i-2)%_mod;
for(int i=1;i<1111111;i++)
for(int j=2*i;j<1111111;j+=i) //枚举倍数减掉多余的
{
ans[j]-=ans[i];
if(ans[j]<0)ans[j]+=_mod;
}
for(int i=2;i<1111111;i++)
{
ans[i]+=ans[i-1];
if(ans[i]>=_mod)ans[i]-=_mod;
}
int T = read();
while(T--) {
long long n = read();
printf("%lld\n", calc(n));
}
return 0;
}