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 and 7.
Input
Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.
The number of datasets is less than or equal to 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以内的素数个数。
解题思路:
典型的素数筛法
核心模板:
void init() {
for (int i = 1; i < maxn; i++) {
mark[i] = false;
}
for (int i = 2; i < maxn; i++) {
if (mark[i])continue;
prime[++cnt] = i;
//虽然《机试指南》这本书中j是从i*i开始的
//这样做能够避免重复工作
//但当i的值较大时,j的值就很可能超出了数据类型所能表示的范围
//我看到网上大部分的代码中j都是从i*2开始的
//不过j从i开始也可以,本人还是习惯从i开始 嘿嘿
for (int j = i; j < maxn; j += i) {
mark[j] = true;
}
}
}
AC代码:
#include<iostream>
#include<stdio.h>
using namespace std;
#define maxn 1000005
bool mark[maxn];
int prime[maxn];
int cnt = 0;
void init() {
for (int i = 1; i < maxn; i++) {
mark[i] = false;
}
for (int i = 2; i < maxn; i++) {
if (mark[i])continue;
prime[++cnt] = i;
for (int j = i; j < maxn; j += i) {
mark[j] = true;
}
}
}
int main() {
int n;
init();
while (scanf("%d", &n) != EOF) {
int i;
for (i = 1; i <= cnt; i++) {
if (prime[i] > n) break;
}
cout << i - 1 << endl;
}
}