简体   繁体   English

大量循环耗时太长

[英]Massive for loop taking too long to load

I'm working on a program designed to generate prime numbers, and I'm trying to find the 10001st prime number. 我正在开发一个旨在生成质数的程序,并且试图找到第10001个质数。 Each time the loop runs, it tests variable i to see if it's divisible by variable j, which is part of another loop that goes up to half of i. 每次循环运行时,它都会测试变量i是否被变量j整除,变量j是另一个循环的一部分,而循环i最多占i的一半。 If i is divisible by j then it adds one to variable prime, and when the loop's done it checks to see if variable prime is larger than two; 如果i被j整除,则将其加到变量质数,并且在循环完成后检查变量质数是否大于2。 if it is, then i is not prime. 如果是,那么我不是素数。 If it is prime, it gets push()ed to the variable array, which stores all the primes. 如果是素数,它将被push()到存储所有素数的变量数组。 Sorry if that's a little confusing. 抱歉,这有点令人困惑。

My problem is that although this code works, whenever I set the first for loop too high (here I have it end at 100000), my browser freezes: 我的问题是,尽管此代码有效,但是每当我将第一个for循环设置得太高(在这里将其结束于100000)时,我的浏览器就会冻结:

var prime = 0;
var array = [];
for(var i = 2; i <= 100000; i+=1) {
  var prime = 0;
  for(var j = 0; j <= i/2; j+=1) {
    if(i % j === 0) {
      prime += 1;
    }
  }

  if(prime < 2) {
    array.push(i);
  }
}

console.log(array.length)

I know I could just copy and paste all the prime numbers but I want to make the program work. 我知道我可以复制并粘贴所有素数,但是我想使程序正常工作。 Any ideas to make the program stop freezing? 有什么想法可以使程序停止冻结吗?

This is because the time complexity of your algorithm is pretty much O(n^2). 这是因为算法的时间复杂度几乎是O(n ^ 2)。 Sieve of Eratosthenes created a better algorithm that will prevent your browser from freezing. Eratosthenes的Sieve创建了一种更好的算法,可以防止浏览器冻结。 Here is one way of doing it: 这是一种实现方法:

var exceptions = {
  2: 2,
  3: 3,
  5: 5,
  7: 7
}

var primeSieve = function (start, end) {
  var result = [];
  for (start; start < end; start++) {
    if (start in exceptions) result.push(start);
    if (start > 1 && start % 2 !== 0 && start % 3 !== 0 && start % 5 !== 0 && start % 7 !== 0) {
      result.push(start);
    }
  }
  return result;
};

You can obviously make this look prettier, but I just did it quickly so you can get the point. 您显然可以使它看起来更漂亮,但是我只是很快完成了操作,所以您可以理解这一点。 I hope this helps! 我希望这有帮助! Let me know if you have further questions. 如果您还有其他问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM