您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Count Primes

2016-02-28 15:53 567 查看

Count Prime

Description:

Count the number of prime numbers less than a non-negative number, n.

https://leetcode.com/problems/count-primes/

找出所有小于n的数中的质数。

删数法。开一个1到n的数组,删除所有2的倍数,3的倍数...直到√n的倍数,最后剩下的就是质数。

/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
var count = 0, i, j, dict = [],
len = Math.floor(Math.sqrt(n));
for(i = 2; i <= len; i++)
for(j = 2; i * j <= n; j++)
dict[i * j] = false;
for(i = 2; i < n; i++)
if(dict[i] === undefined) count++;
return count;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: