Wednesday, December 19, 2018

204. Count Primes

Version #1 Array of  multiples
Check this reference
https://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/

二刷
61.00 %
class Solution {
    public int countPrimes(int n) {
        boolean[] notPrime = new boolean[n]; // default all primes
        for (int i = 2; i < n; i++) {
            if (notPrime[i]) {
                continue;
            }
            for (int k = 2 * i; k < n; k += i) {
                notPrime[k] = true;
            }
        }
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (!notPrime[i]) {
                count++;
            }
        }
        return count;
    }
}

一刷
53.10 %
class Solution {
    public int countPrimes(int n) {
// 0 - n-1 -> n numbers, 0,1 don't count
if (n <= 1) return 0;
int count = 0;
boolean[] notPrime = new boolean[n];
for (int i = 2; i < n; i++) {
if (!notPrime[i]) {
count++;
for (int j = 2; j * i < n; j++) {
notPrime[j * i] = true;
}
}
}
return count;
}
}

No comments:

Post a Comment