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
#include <cstdio> #include <vector> using namespace std; class Factor { public: vector<bool> is_prime;//pi : min prime factor vector<int> prime, pi; int sieve(int sz) { int cnt = 0; is_prime.resize(sz + 1, false); pi.resize(sz + 1, 0); for (int i = 1; i <= sz; i++) { pi[i] = i; } for (int i = 2; i <= sz; i++) { if (pi[i] == i) { prime.push_back(i); is_prime[i] = true; ++cnt; } for (int j = 0; j < cnt && 1LL * prime[j] * i <= sz; j++) { pi[prime[j] * i] = prime[j]; if (i % prime[j] == 0) { break; } } } return cnt; } }; const int MAXN = 1e6 + 10; int ans[MAXN]; int main() { Factor fa; int n = 1000000; fa.sieve(n); for (int i = 1; i <= n; i++) { ans[i] = ans[i - 1] + fa.is_prime[i]; } int x; while (~scanf("%d", &x)) { printf("%d ", ans[x]); } return 0; }