LeetCode-Count Primes
阿新 • • 發佈:2018-12-16
Description: 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.
題意:給定一個正整數,統計所有小於這個數的素數的個數;
解法一(超時):最簡單的辦法就是遍歷所有小於這個數的元素,計算是否為素數後統計即可;但是,其時間複雜度為O(n1.5);
Java
class Solution { public int countPrimes(int n) { int cnt = 0; for (int i = 2; i < n; i++) { cnt = isPrime(i) ? cnt + 1 : cnt; } return cnt; } private boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return n == 1 ? false : true; } }
解法二:參考Sieve of Eratosthenes知道,假如已經判斷了2為素數,那麼所有2的倍數都不是素數,3為素數,所有3的倍數都不是素數,4不是素數,4的所有倍數也都不是素數…依次可統計素數個數;
Java
class Solution { public int countPrimes(int n) { int cnt = 0; boolean[] table = new boolean[n]; for (int i = 2; i < n; i++) { if (!table[i]) { cnt = isPrime(i) ? cnt + 1 : cnt; for (int j = 2; j * i < n; j++) table[j * i] = true; } } return cnt; } private boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return n == 1 ? false : true; } }