Prime Number
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5, 7.
Input
Input consists of several datasets. Each dataset has an integer n (n ≤ 999999) in a line.
The number of datasets ≤ 30.
Output
For each dataset, prints the number of prime numbers.
Sample Input
10
3
11
Output for the Sample Input
4
2
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5, 7.
Input
Input consists of several datasets. Each dataset has an integer n (n ≤ 999999) in a line.
The number of datasets ≤ 30.
Output
For each dataset, prints the number of prime numbers.
Sample Input
10
3
11
Output for the Sample Input
4
2
5
给出一个数n,求n以内素数的个数。我用的埃氏筛法
#include <cstdio>
#include <iostream>
using namespace std;
int prime[1000005];
bool is_prime[1000005];
int seve(int n)
{
int p=0;
for(int i=0;i<=n;i++)
is_prime[i]=true;
is_prime[0]=is_prime[1]=false;
for(int i=2;i<=n;i++)
{
if(is_prime[i])
{
prime[p++]=i;
for(int j=2*i;j<=n;j+=i)
is_prime[j]=false;
}
}
return p;
}
int main(void)
{
int n;
while(scanf("%d",&n)!=EOF)
{
printf("%d\n",seve(n));
}
return 0;
}