- 1000ms
- 512000K
A square-free integer is an integer which is indivisible by any square number except 11. For example, 6 = 2 * 3=1⋅6 is square-free, but 12 = 2^2 *3 is not, because 2^2 is a square number. Some integers could be decomposed into product of two square-free integers, there may be more than one decomposition ways. For example, 6=6*1=1*6=2*3=3*2,n=a*b and n=b*a are considered different if a != b f(n) is the number of decomposition ways that n=a*b such that a and b are square-free integers. The problem is calculating \sum_{i = 1}^nf(i)∑i=1nf(i).
Input
The first line contains an integer T(T<= 20), denoting the number of test cases.
For each test case, there first line has a integer n(n≤2⋅107).
Output
For each test case, print the answer \sum_{i = 1}^n f(i)∑i=1n f(i).
Hint
\sum_{i = 1}^8 f(i)=f(1)+ \cdots +f(8)∑i=18f(i)=f(1)+⋯+f(8)
=1+2+2+1+2+4+2+0=14=1+2+2+1+2+4+2+0=14.
样例输入复制
2
5
8
样例输出复制
8
14
题目来源
线性筛预处理:
整体思想就是线性筛出n内所有素数同时标记一下这个数质因子。最后线性处理根据这个数的质因子的指数确定这个数的答案然后处理前缀和。
我们判断这个数的非平方数的乘积个数。我们可以知道n的无平方数的乘积个数为:我们假设n的一个质因子为d[n],n可以拆成d[n]^num*x,则ans[n]为 if(num==1) ans[n]=ans[x]*2, else if(num==2) ans[n]=ans[x]. else if(num>2) ans[n]=0。
#include<bits/stdc++.h> const int maxn = 2*1e7+5; typedef long long ll; using namespace std; bool isprime[maxn]; int d[maxn],prime[maxn],ans[maxn]; ll sum[maxn]; void init() { int cnt=0; for(int i=2;i<maxn;i++) { if(!isprime[i]){ prime[cnt++]=i; } for(int j=0;j<cnt&&1ll*i*prime[j]<maxn;j++) { isprime[i*prime[j]]=true; d[i*prime[j]]=prime[j]; if(i%prime[j]==0)break; } } sum[1]=1; ans[1]=1; for(int i=2;i<maxn;i++) { if(!isprime[i]) ans[i]=2; else{ int x=i,num=0; while(x%d[i]==0){ x/=d[i]; num++; if(num>2) break; } if(num==1) ans[i]=ans[x]*2; else if(num==2) ans[i]=ans[x]; else ans[i]=0; } sum[i]=sum[i-1]+ans[i]; } } int main() { int t,n; init(); scanf("%d",&t); while(t--){ scanf("%d",&n); printf("%lld\n",sum[n]); } return 0; }
整除分块:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool v[20000010];
int cnt[20000010];
void init()
{
for(int i=2;i*i<=20000000;i++)
{
int now=i*i;
v[now]=1;
for(int j=2;j*now<=20000000;j++) v[j*now]=1;
}
cnt[0]=0;
for(int i=1;i<=20000000;i++)
if(v[i]==1) cnt[i]=cnt[i-1]+1;
else cnt[i]=cnt[i-1];
}
int t,n;
int main()
{
init();
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int ans=0;int tim;
for(int i=1;i<=n;i=tim+1)
{
tim=n/(n/i);
int num=(tim-i+1-cnt[tim]+cnt[i-1]);
ans+=num*(n/i);
ans-=num*cnt[n/i];
}
printf("%d\n",ans);
}
return 0;
}