找到250以下的素数之和 [英] finding sum of prime numbers under 250

查看:382
本文介绍了找到250以下的素数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var sum = 0

for (i = 0; i < 250; i++) {

    function checkIfPrime() {

        for (factor = 2; factor < i; factor++) {
            if (i % factor = 0) {
                sum = sum;
            }
            else {
                sum += factor;
            }
        }
    }
}

document.write(sum);

我正在尝试检查250以下所有素数的总和。我收到错误说我在声明中无效if if(i%factor = 0)我知道是在原始for语句中创建的,但有没有办法在if中引用它声明?

I am trying to check for the sum of all the prime numbers under 250. I am getting an error saying that i is invalid in the statement if (i % factor = 0) I know was creating in the original for statement, but is there any way to reference it in the if statement?

推荐答案

通过素数计算,您是否考虑过使用 Eratosthenes的筛子?这是一种更优雅的方法来确定素数,并且总结结果很简单。

With the prime computation, have you considered using Sieve of Eratosthenes? This is a much more elegant way of determining primes, and, summing the result is simple.

var sieve = new Array();
var maxcount = 250;
var maxsieve = 10000;

// Build the Sieve, marking all numbers as possible prime.
for (var i = 2; i < maxsieve; i++)
    sieve[i] = 1;

// Use the Sieve to find primes and count them as they are found.
var primes = [ ];
var sum = 0;
for (var prime = 2; prime < maxsieve && primes.length < maxcount; prime++)
{
    if (!sieve[prime]) continue;
    primes.push(prime); // found a prime, save it
    sum += prime;
    for (var i = prime * 2; i < maxsieve; i += prime)
        sieve[i] = 0; // mark all multiples as non prime
}

document.getElementById("result").value =
      "primes: " + primes.join(" ") + "\n"
    + "count: " + primes.length + "\n"
    + "sum: " + sum + "\n";

#result {
    width:100%;
    height:180px
}

<textarea id="result">
</textarea>

(编辑)随着更新算法,现在有两个最大参与:

(EDIT) With the updated algorithm, there are now two max involved:


  • maxcount 是您希望找到的素数的最大数量

  • maxsieve 是对筛子的猜测,其大小足以包含 maxcount primes

  • maxcount is the maximum number of prime numbers you wish to find
  • maxsieve is a guess of sieve large enough to contain maxcount primes

您必须通过实际检查真实的计数来验证这一点,因为有两个终止条件(1)我们达到了筛网的极限并且找不到更多素数,或(2)我们实际上找到了我们正在寻找的东西。

You will have to validate this by actually checking the real count since there are two terminating conditions (1) we hit the limit of our sieve and cannot find any more primes, or (2) we actually found what we're looking for.

如果你要将数字增加到远大于250的数字,那么Sieve就不再变得可行,因为它将消耗大量的记忆。无论如何,我认为这一切都有道理吗?你现在真的需要自己玩Sieve而不是依赖我对它的解释。

If you were to increase the number to numbers much greater than 250, than the Sieve no longer becomes viable as it would be consume great deals of memory. Anyhow, I think this all makes sense right? You really need to play with the Sieve yourself at this point than rely on my interpretation of it.

这篇关于找到250以下的素数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆