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.
求n以内有多少个素数?
解法:
var countPrimes = function(n) {
const ans = Array(n).fill(true);//设置一个全是true的数组,默认全是素数。
let count = 0;
for(var i = 2;i<n;i++){//因为2是素数,从2开始。
if(ans[i]){//如果是此数组为true就代表是素数,count加1。如果是false则不往下走。
count++;
for(var j = 2;i*j<n;j++){//因为i是素数,说明i的倍数就不是素数。所以循环i的倍数,让它等于false。
ans[i*j] = false;
}
}
}
return count;//最后返回count的个数。
};
启发自:https://blog.youkuaiyun.com/ace_arm/article/details/79019704