zoukankan      html  css  js  c++  java
  • Prime Number Aizu

    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;
    }
  • 相关阅读:
    FastDFS的简单使用
    KindEditor的简单使用
    rpc
    SDS——动态字符串
    图的深度优先遍历和广度优先遍历
    innodb和myisam原理
    cap理论
    冒泡排序
    桥接模式
    适配器模式
  • 原文地址:https://www.cnblogs.com/xxxsans/p/12755982.html
Copyright © 2011-2022 走看看