Count Primes - Javascript

来源:互联网 发布:宣传视频制作软件 编辑:程序博客网 时间:2024/06/06 13:07

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;};


0 0
原创粉丝点击