[Challenge] Sum All Primes - Inifite Loop

[Challenge] Sum All Primes - Inifite Loop


I was trying to use a Sieve of Eratosthenes snippet from one of my favorite snippet repositories (rosettacode.com) and the code works as intended in dev tools (tried a couple browsers to make sure), but when I run it in the FCC tool it only works up to submitting 15 as the argument after that I get an infinite loop message. I’ve walked through it a couple times but I just can’t figure out the issue.

I’ve found other solutions, but I really would like to know why it didn’t work since I use rosettacode a bunch. Is there a problem in the code that I just can’t identify or is it a quirk of the FCC code?

Here is the code, and when I run it through FCC it says reports “Potential infinite loop at line 14” (var p = nums[i])

function sumPrimes(num) {
  var sumOfPrimes = 0;
  var allThePrimes = [];

  // Find primes using Sieve of Eratosthenes (https://rosettacode.org/wiki/Sieve_of_Eratosthenes#JavaScript)
  function eratosthenes(limit) {
    var primes = [];
    if (limit >= 2) {
        var sqrtlmt = Math.sqrt(limit) - 2;
        var nums = []; // start with an empty Array...
        for (var i = 2; i <= limit; i++) // and
            nums.push(i); // only initialize the Array once...
        for (var i = 0; i <= sqrtlmt; i++) {
            var p = nums[i];
            if (p)
                for (var j = p * p - 2; j < nums.length; j += p) {
                  nums[j] = 0;
        for (var i = 0; i < nums.length; i++) {
            var p = nums[i];
            if (p)
    return primes;
  allThePrimes = eratosthenes(num);

  // Sum prime numbers in allThePrimes
  for (var i = 0; i < allThePrimes.length; i++) {
    sumOfPrimes += allThePrimes[i];

  return sumOfPrimes;


Thanks in advance.


The infinite loop detection is timing based, so if your code is slow it will send up the warning to save you from locking up your browser. You can turn the loop protection off, but always do this very cautiously.