题目
传送门
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), agcd(a,b), bgcd(a,b) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a+b>c, b+c>a and c+a>b.
In a group of numbers, a number is lonely if it doesn’t have any friends in that group.
Given a group of numbers containing all numbers from 1,2,3,…,n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1≤t≤106) - number of test cases.
On next line there are t numbers, ni (1≤ni≤106) - meaning that in case i you should solve for numbers 1,2,3,…,ni.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1,2,3,…,ni.
输入
3
1 5 10
输出
1
3
3
题意:t个数,下面是n1~nt,对于每个ni我们要求出1—ni共有多少个孤独数字,孤独数字的定义为1-n中,某个数字a对任意的数字b都不满足gcd(a,b), a/gcd(a,b), b/gcd(a,b)可以构成三角形;
思路:暴力打表之后我们可以发现孤独数字都是素数,但是有的素数不是孤独数字当且仅当他的平方出现在1-ni中,所以n的范围是1e6,我们可以先筛出范围内的所有数字再用前缀和打表求解,具体看代码;
AC code
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<sstream>
#include<queue>
#include<stack>
using namespace std;
int ans[1200000],prim[1200000],num[1200000],pn=0;
int n;
void table()
{
memset(num,-1,sizeof(num));
for(int i=2;i<1000010;i++)
{if(num[i])prim[pn++]=i;
for(int j=0;j<pn&&i*prim[j]<1000010;j++)
{num[i*prim[j]]=0;
if(i%prim[j]==0)break;}
}//线性筛模板
for(int i=0;i<pn;i++)
{
if(prim[i]<=1000)ans[prim[i]*prim[i]]--;//如果素数的平方出现,那么就要减去这个素数,此时这个素数将不再是孤独数字
ans[prim[i]]++;
}
ans[1]=1;
for(int i=2;i<1000001;i++)ans[i]+=ans[i-1];//前缀和
}
void solve()
{
printf("%d\n",ans[n]);
}
int main()
{
ios::sync_with_stdio(0);
table();
int t;
cin>>t;
while(t--)
{
cin>>n;
solve();}
}