微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

你能解释一下这种在javascript中查找素数的方法吗?

function getPrimes(max) {
var sieve = [],i,j,primes = [];
for (i = 2; i <= max; ++i) {
    if (!sieve[i]) {
        // i has not been marked -- it is prime
        primes.push(i);
        for (j = i << 1; j <= max; j += i) {
            sieve[j] = true;
        }
    }
}
return primes;
}

我明白我跟踪所有数字.

我不明白……!筛[i],j = i<< 1; &安培;真正发生了什么. 只是为了清楚.素数是一个只能被它自己或一个整除的东西.

解决方法

它使用了Eratosthenes的Sieve.

来自维基百科(http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

A prime number is a natural number which has exactly two distinct
natural number divisors: 1 and itself.

To find all the prime numbers less than or equal to a given integer n
by Eratosthenes’ method:

  • Create a list of consecutive integers from 2 to n: (2,3,4,…,n).
  • Initially,let p equal 2,the first prime number.
  • Starting from p,count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of
    p: 2p,3p,4p,etc.; note that some of them may have already been
    marked.
  • Find the first number greater than p in the list that is not marked. If there was no such number,stop. Otherwise,let p Now equal
    this number (which is the next prime),and repeat from step 3.

When the algorithm terminates,all the numbers in the list that are not marked are prime. The main idea here is that every value for p is prime,because we have already marked all the multiples of the numbers less than p.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐