Sum All Primes Got lost

Tell us what’s happening:
I have a bunch of pieces but seem to be going nowhere. Can someone please direct me with what I have to do to make it all work.

Your code so far


function getSum(total, num) {
  return total + num;
}

var n= 10;
function test_prime(n)
{

  if (n===1)
  {
    return false;
  }
  else if(n === 2)
  {
    return true;
  }else
  {
    for(var x = 2; x < n; x++)
    {
      if(n % x === 0)
      {
        return false;
      }
    }
    return true;  
  }
}

console.log(test_prime(n));

const myArray = []
for (let i = 0; i < n; i++) {
  myArray.push(i)
}
console.log(myArray);

var filtered= myArray.filter(test_prime);
console.log(filtered);
var final= filtered.reduce(getSum);
console.log(final);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/

I will help you get started.

  1. You currently do not have a function named sumPrimes which returns the final sum.

  2. You should not hard-code n. It needs to be a parameter of your sumPrimes function.

1 Like

Here is what I did. What to do to clean it?


function sumPrimes(n){
function add(total, num) {
  return total + num;
}

function test_prime(n)
{

  if (n===1)
  {
    return false;
  }
  else if(n === 2)
  {
    return true;
  }else
  {
    for(var x = 2; x < n; x++)
    {
      if(n % x === 0)
      {
        return false;
      }
    }
    return true;  
  }
}

const myArray = []
for (let i = 0; i <= n; i++) {
  myArray.push(i)
}
console.log(myArray);

var filtered= myArray.filter(test_prime);
var final= filtered.reduce(add);
  return final;
}
sumPrimes(10);

One thing you could do…
If a number is not divisible by 3, do you really need to also check if it is divisible by 6,9,12,15 etc ?
You would need to re arrange things a bit, but it is not a complicated change

2 Likes