Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Tags
Hash Table, Math
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
// Prime Numbers within 10
// 2 3 5 7 9
if(n <= 1) {
return 0;
}
// 排除法,找到質數,排除其所有的倍數
var exclude = [];
for(var i=2;i<n;i++) {
var k=2;
while( i*k < n) {
if(!exclude[i*k]) {
exclude[i*k] = true;
}
k++;
}
}
// 搜索1~n排除後剩下的數據
var ans = 0;
for (var p = 2; p < n; p++) {
if (!exclude[p]) {
ans++;
}
}
return ans;
};