简体   繁体   English

Project Euler - 问题 3:如何使我的 Eratosthenes 筛实施正常工作?

[英]Project Euler - Problem 3: How to make my Sieve of Eratosthenes implementation work properly?

So I'm trying to solve the third problem of Project Euler in which you have to get the largest prime factor of a number.所以我试图解决 Project Euler 的第三个问题,在这个问题中你必须得到一个数的最大素数。 I'm trying this problem via freeCodeCamp .我正在通过 freeCodeCamp尝试这个问题。 I pass all tests of 2, 3, 5, 7, 8 and 13195, but from 13195 and upwards I get a Potential infinite loop detected on line 12. Tests may fail if this is not changed.我通过了 2、3、5、7、8 和 13195 的所有测试,但从 13195 及更高版本开始,我Potential infinite loop detected on line 12. Tests may fail if this is not changed. warning.警告。 The final test of 600851475143 gives the following warnings: 600851475143 的最终测试给出以下警告:

Potential infinite loop detected on line 6. Tests may fail if this is not changed.
Potential infinite loop detected on line 15. Tests may fail if this is not changed.
Potential infinite loop detected on line 12. Tests may fail if this is not changed.

and the horribly wrong answer of 104441.以及 104441 的可怕错误答案。

What could I have done wrong, since my loops don't look like they would run infinitely syntax-wise?我做错了什么,因为我的循环看起来不像它们会在语法上无限运行? Am I missing something here?我在这里错过了什么吗?

Code I'm using:我正在使用的代码:

const eratoSieve = (n) => {
  let primes = [2, 3, 5, 7];
  if (n > 7)
  {
    primes = [];
    for (let i = 2; i < n; i++)
    {
      primes.push(i);
    }
  }

  for (let j = 0; j < primes.length; j++)
  {
    let currentMultiple = primes[j];
    for (let k = j + 1; k < primes.length - 1; k++)
    {
      if (primes[k] % currentMultiple === 0)
      {
        primes.splice(k, 1);
      }
    }
  }
  return primes;
};

function largestPrimeFactor(number) {
  let primeNums = eratoSieve(number);
  console.log(primeNums);
  let biggestPrime = 0;
  primeNums.forEach(elem => {
    (number % elem === 0) ? biggestPrime = elem : 0;
  });
  return biggestPrime;
}

console.log(largestPrimeFactor(100));

Thanks in advance for the help!在此先感谢您的帮助!

You can't do 600 billion loops.你不能做 6000 亿次循环。 Let's assume each number took up only 1 bit of storage(thats not the reality), then that would come up to over 70 GB of data from just the first portion of your code alone.假设每个数字仅占用 1 位存储空间(事实并非如此),那么仅您的代码的第一部分就会产生超过 70 GB 的数据。

Your method works in theory but is too inefficient to be practical for such large numbers.您的方法在理论上有效,但对于如此大的数字来说效率太低而无法实用。

Hint for this problem:这个问题的提示:

-For each factor that divides into a number, the number of remaining possible factors that need to be checked will be reduced. -对于每个划分为一个数字的因素,将减少需要检查的剩余可能因素的数量。

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

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