Prime Number
Time Limit : 1 sec, Memory Limit : 65536 KB
Japanese version is here
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 5
水题,素数筛选。
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 6 using namespace std; 7 8 #define maxn 999999 + 5 9 typedef long long ll; 10 11 int prime[maxn]; 12 13 void init() { 14 for(int i = 2; i <= maxn - 5; i++) { 15 prime[i] = i % 2; 16 } 17 18 prime[2] = 1; 19 20 for(int i = 2; i * i <= maxn; i++) { 21 if(!prime[i]) continue; 22 for(int j = i; j * i <= maxn; j++) { 23 prime[j * i] = 0; 24 } 25 } 26 27 for(int i = 1; i <= maxn - 5; i++) { 28 prime[i] += prime[i - 1]; 29 } 30 } 31 32 int main() { 33 int n; 34 init(); 35 while( ~scanf("%d",&n)) { 36 printf("%d ",prime[n]); 37 } 38 39 return 0; 40 41 42 }