Sum All Primes - Problem

Sum All Primes - Problem
0

#1

Following code works for numbers less than 200 but giving wrong sum for greater than 200 numbers?

function sumPrimes(num) {
  numbers = [];
  sums = 0;
  
  for(i=2;i<num;i++)
  {
  	numbers.push(i);
  }
  
  for(i=0;i<numbers.length;i++)
  {
  	if(numbers[i]%2===0 && numbers[i]!==2){
  		numbers.splice(i,1);
  	}
  }
  
  for(i=0;i<numbers.length;i++)
  {
  	if(numbers[i]%3===0 && numbers[i]!==3){
  		numbers.splice(i,1);
  	}
  }
  
  for(i=0;i<numbers.length;i++)
  {
  	if(numbers[i]%5===0 && numbers[i]!==5){
  		numbers.splice(i,1);
  	}
  }
  
  for(i=0;i<numbers.length;i++)
  {
  	sums += numbers[i];
  }

console.log(numbers)

  return sums;
}
sumPrimes(977);  

#2

You are checking your list of numbers for divisibility by a small bunch of primes only (2, 3, 5). 49 is obviously not a prime (it’s 7*7), but it will slip through your algorithm and get added to the sum. You could type in another for loop checking for multiples of 7 and so on… but I think you need a more generic way.


#3

I had added multiples up to 29 but the problem was that I got the wrong results for bigger values like sumPrimes(977)


#4

Which won’t help you, because next prime is 31, and 31*31 is 961 (not a prime number, and not a multiple of any prime you have checked). This is less than 977 and will get added to your sum, making the result wrong.

You should try to find out a solution that can handle any number (well, any number you can fit into memory, but let’s skip over that :wink: ). The solution you have has the problem that for a very big number you will need lots of code, and you’d have to know all the primes less than this number in advance.


#5

What would be the best algorithm because I coded above solution after reading about Sieve of Eratosthenes supports only lower values?


#6

As far as I know the sieve should work for any input size. I submitted a solution that uses sieve of Eratosthenes and it can run well up to around 22000 before the FCC code editor warns about a potential infinite loop (which I’m confident is not true).


#7

thanks for this post. it got me to see my mistake :grinning:
i got it to work like this :+1:

function sumPrimes(num) {
  var num1 = 2;
  var count =2;
  var arr = [2];
  var checker = true;
  
  while (num1<=num) {
   for (i=0;i<=arr.length;i++) {
     //return num1%arr[i];
     if (num1%arr[i]==0) {
       checker = false;
       break;
     }
     
   }
    if (checker ==true) {
       arr.push(num1);
       count +=num1;
     } else {
       checker = true;
     }
    num1++;
  }
  
  return count;
}

sumPrimes(977);