Sum all primes (please review my code)

Sum all primes (please review my code)
0.0 0

#1

Hi everyone!

i can obtain the primes with this code, but the sum of 977 is not equal with the given one (73156). the primes array is like so:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 121, 127, 131, 137, 139, 143, 149, 151, 157, 163, 167, 169, 173, 179, 181, 187, 191, 193, 197, 199, 209, 211, 221, 223, 227, 229, 233, 239, 241, 247, 251, 253, 257, 263, 269, 271, 277, 281, 283, 289, 293, 299, 307, 311, 313, 317, 319, 323, 331, 337, 341, 347, 349, 353, 359, 361, 367, 373, 377, 379, 383, 389, 391, 397, 401, 403, 407, 409, 419, 421, 431, 433, 437, 439, 443, 449, 451, 457, 461, 463, 467, 473, 479, 481, 487, 491, 493, 499, 503, 509, 517, 521, 523, 527, 529, 533, 541, 547, 551, 557, 559, 563, 569, 571, 577, 583, 587, 589, 593, 599, 601, 607, 611, 613, 617, 619, 629, 631, 641, 643, 647, 649, 653, 659, 661, 667, 671, 673, 677, 683, 689, 691, 697, 701, 703, 709, 713, 719, 727, 731, 733, 737, 739, 743, 751, 757, 761, 767, 769, 773, 779, 781, 787, 793, 797, 799, 803, 809, 811, 817, 821, 823, 827, 829, 839, 841, 851, 853, 857, 859, 863, 869, 871, 877, 881, 883, 887, 893, 899, 901, 907, 911, 913, 919, 923, 929, 937, 941, 943, 947, 949, 953, 961, 967, 971, 977]

as i tested randomly, the numbers are prime. but why doesn’t give the required result? could you tell me please, where is the wrong?

thank you.

function sumPrimes(num) {

  var arr = [];
  var sum = 0;

  for (var i = 2; i <= num; i++) {
    arr.push(i);

    for (var n = 2; n < arr.length; n++) {
      if (arr[n] % 2 === 0) {
        arr.pop(arr[n]);
      }
    }
    for (var j = 3; j < arr.length; j++) {
      if (arr[j] % 3 === 0) {
        arr.pop(arr[j]);
      }
    }
    for (var k = 5; k < arr.length; k++) {
      if (arr[k] % 5 === 0) {
        arr.pop(arr[k]);
      }
    }
    for (var m = 7; m < arr.length; m++) {
      if (arr[m] % 7 === 0) {
        arr.pop(arr[m]);
      }
    }
  }

  for (var x in arr) {
    sum += arr[x];
  }

  return sum;
}

sumPrimes(10);


#2

Hi, your code works fine when you pass in 10, but the logic doesn’t hold for bigger numbers. Keep in mind that 11, 13, 17 and many other numbers are also prime. Having a for loop for each prime number is not sustainable. Try to come up with different logic for finding if a number is prime, e.g. start from 2 up to the number and if the number is divisible by the current iteration then it’s not prime.

Another issue is that the Array.pop() method in JS doesn’t take any arguments and it will remove the last element of the array.


#3

thank you for your comment, and advice vdineva,
i’ll try the way what you offer.