1. 程式人生 > >[leetcode]204.Count Primes

[leetcode]204.Count Primes

mes solution The 數組 count prime otp num xpl

題目

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;
    }
}

[leetcode]204.Count Primes