sammyb123 sammyb123 - 23 days ago 9
Javascript Question

Sum in nested loops returning incorrect

Not sure what is wrong here but I am trying to add a set of numbers in an array (not the whole array) but it looks like it is summing up the whole array:



function sumPrimes(num) {
var arr = [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];
var total = 0;
var index;
//loop through the whole array
for (var i = 0; i < arr.length; i++) {
//find matching prime number
if (num < arr[i]) {
// get index of prime number in the array
index = arr.indexOf(arr[i]);
//sum up total of prime numbers up to 'num'
for (var b = 0; b < index; b++) {
total = total + arr[index];
}
}
}
return total;
}
sumPrimes(10);




Answer

If your goal is to calculate the sum of all prime numbers less than the given number, then the solution is much easier.

Either

function sumPrimes(num) {
    var arr = [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];

    var total = 0;

    for (var x of arr) {
        if (x < num)
            total += x;
        else
            break;
    }

    return total;
}

which works when arr is sorted, or

function sumPrimes(num) {
    var arr = [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];

    var total = 0;

    arr.forEach(function(x) {
        if (x < num)
            total += x; 
    }, this);

    return total;
}

that would work for an unsorted array as well.