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.
思路
1.暴力解法: 挨個數字遍歷,計算是否為素數.
計算一個數字是否為素數,time O(n)
全部算完: 時間 O (n*n) 空間 O(1)
2.使用一個長度為n的boolean臨時數組,標記是否為素數。
遍歷元素i,從2開始
如果flag為 非素數,count++;
并且計算i乘以一個倍數j(j從2開始,依次++),只要 i*j = m < n 則標記 m 非素數
等所有數字標記完成,素數個數count就統計完成了
time:O(nlogn)? space: O(n)
參考:https://zhengyang2015.gitbooks.io/lintcode/count-primes-leetcode-204.html 動畫很清晰顯示了思路
下面的代碼跟參考文章思路類型,稍微優化的版本。
public int countPrimes(int n){
boolean[] notPrimes = new boolean[n];//默認全部為false
int count = 0;
for(int i = 2; i < n;i++){
if(notPrimes[i] == false){
count++;
}
for(int j = 2;j < n;j++){
if(i * j < n){
notPrimes[i*j] = true;
}
}
}
return count;
}