[leetcode]204.Count Primes

题目

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

解法一

思路

上来直接用的暴力解法,然而有3个case超时了

代码

class Solution {
    public int countPrimes(int n) {
        int res = 0;
        for(int i = 1; i < n; i++) {
            if(isPrime(i)) res++;
        }
        return res;
    }
    private boolean isPrime(int n) {
        int count = 0;
        if(n == 1) return false;
        for(int i = 1; i * i <= n; i++) {
            if(n % i == 0) count++;
        }
        return count == 1 ? true : false;
    }
}

解法二

思路

用的是埃拉托斯特尼筛法

代码

class Solution {
    public int countPrimes(int n) {
        boolean[] notPrime = new boolean[n];
        int count = 0;
        for(int i = 2; i < n; i++) { //遍历数组
            if(notPrime[i])
                continue;
            
            count++;
            
            for(int j = 2; i * j < n; j++)
                notPrime[i * j] = true;
            
        }
        return count;
    }
}

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9777404.html
今日推荐