I made a function to check if a number is a prime number or not, if not, then it returns the number, otherwise(if it is a prime number) it returns 0.
var maybePrimeNumber = [5, 8, 11, 14, 17, 20, 23, 28, 31]; //numbers to test
function isNotPrime(integer){
var prime = true; //start off assuming that it is a prime nr for now
var returnNumber = 0; //to be returned at the end
for(i = 2; i<integer; i++){ //go from 2 up to the number,
if(integer % i === 0){ //if the number is divisible by any nr between 2 and itself,
prime = false; //then say that it isn't a prime number
}
}
if(!prime){ //if it isn't a prime number, then
returnNumber = integer; //prepare to send back the number
}
return returnNumber;
}
document.getElementById("demo").innerHTML = maybePrimeNumber.reduce(
(total, integer) => {return total + isNotPrime(integer)}
);
//sum all non-prime numbers up from the array and put the sum into the paragraph "demo"
And the problem is as follows:
When I run this, it gives me 75, but it should be giving me 70.
So when I replace the last line with this:
document.getElementById("demo").innerHTML = isNotPrime(maybePrimeNumber[0]);
To check if it mistakenly calculates 5 to be a non-prime number - it returns 0, so it doesn't miscalculate.
Why does it give the sum 75 instead of 70 then??
total- to be0- else it'll be the first number in the array, which is5, hence your5off answer. See: jsfiddle.net/88gx55tm