Prime Number
Time Limit : 1 sec, Memory Limit : 65536 KB
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
题意:
输出 N (<= 999999)以内素数的个数。
思路:
素数筛选法。
AC:
#include <stdio.h>
#include <string.h>
#define MAX 1000000
int pri[MAX];
void make_pri() {
memset(pri,0,sizeof(pri));
for(int i = 2;i < MAX;i++) {
if(pri[i]) continue;
for(int j = i + i;j < MAX;j += i) pri[j] = 1;
}
}
int main() {
int n;
make_pri();
while(~scanf("%d",&n)) {
int sum = 0;
for(int i = 2;i <= n;i++)
if(!pri[i]) sum++;
printf("%d\n",sum);
}
return 0;
}