204. 计数质数

统计所有小于非负整数 n 的质数的数量。

示例 1:

输入:n = 10
输出:4
解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
示例 2:

输入:n = 0
输出:0
示例 3:

输入:n = 1
输出:0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-primes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

埃式筛

import java.util.Scanner;

class Solution {

    private static int[] cnt = new int[5000001];

    static {
        boolean[] isNotPrime = new boolean[5000001];
        isNotPrime[0] = true;
        isNotPrime[1] = true;
        for (int i = 4; i <= 5000000; i += 2) {
            isNotPrime[i] = true;
        }
        for (int i = 3; i <= 5000000; i += 2) {
            if (!isNotPrime[i]) {
                if ((long) i * i <= 5000000) {
                    for (int j = i * i; j <= 5000000; j += i) {
                        isNotPrime[j] = true;
                    }
                }
            }
        }

        for (int i = 1; i <= 5000000; ++i) {
            if (!isNotPrime[i]) {
                cnt[i] = cnt[i - 1] + 1;
            } else {
                cnt[i] = cnt[i - 1];
            }
        }
    }

    public int countPrimes(int n) {
        if (n == 0) {
            return 0;
        }
        return cnt[n - 1];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().countPrimes(in.nextInt()));
        }
    }
}

线性筛

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

class Solution {

    private static int[] cnt = new int[5000001];

    static {
        boolean[] isPrime = new boolean[5000001];
        Arrays.fill(isPrime, true);
        isPrime[0] = false;
        isPrime[1] = false;
        List<Integer> primes = new ArrayList<>();

        for (int i = 2; i <= 5000000; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
            for (int j = 0; j < primes.size() && primes.get(j) * i <= 5000000; ++j) {
                isPrime[i * primes.get(j)] = false;
                if (i % primes.get(j) == 0) {
                    break;
                }
            }
        }

        for (int i = 1; i <= 5000000; ++i) {
            if (isPrime[i]) {
                cnt[i] = cnt[i - 1] + 1;
            } else {
                cnt[i] = cnt[i - 1];
            }
        }
    }

    public int countPrimes(int n) {
        if (n == 0) {
            return 0;
        }
        return cnt[n - 1];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().countPrimes(in.nextInt()));
        }
    }
}
上一篇:第三方API(jqdatasdk)获取实时行情数据


下一篇:leetcode数组中级-Lc229.求众数II