Given a positive integer n, please find the number of prime numbers in 1 ~ n.
The input format
consists of one line, including the integer n.
The output format
consists of one line and contains an integer representing the number of prime numbers in 1 ~ n.
Data range
1≤n≤106
Input sample:
8
Output sample:
4
Time complexity: O (nlogn)
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10000;
int prime[N];
int n;
bool st[N];
int main()
{
scanf("%d",&n);
int cnt=0;
memset(st,false,sizeof st);
for(int i=2;i<=n;i++)
{
if(!st[i]) prime[++cnt]=i;
for(int j=1;prime[j]<=n/i&&j<=cnt;j++)
{
st[prime[j]*i]=true;
if(i%prime[j]==0) break;
}
}
cout<<cnt<<endl;
}