LeetCode 204. Count Primes 计数质数 (数论)

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

示例:

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

题解:

经典的判断素数的解法,只要 不能被 2- N 的所有整数整除就是素数,会超时。

class Solution {
    public int countPrimes(int n) {
        if(n<=1){
            return 0;
        }
        int count=0;
        for(int i=2;i<n;i++){
            int j;
            for(j=2;j<=Math.sqrt(i);j++){
                if(i%j==0){
                    break;
                }
            }
            if(j>Math.sqrt(i)){
                count++;
            }
        }
        return count;
    }
}

厄拉多塞筛法
用一个数组表示该位置上的数是否是质数,从2开始,如果是质数,就将他前面所有该质数的倍数的数的位置都标记为非质数。

class Solution {
    public int countPrimes(int n) {
        if (n <= 1) {
            return 0;
        }
        boolean[] a = new boolean[n];//是素数
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (a[i] == false) {// 是素数
                count++;
                for (int j = 2; j * i < n; j++) {
                    a[j * i] = true;
                }
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/80753237