var sum = 0
for (i = 0; i < 250; i++) {
function checkIfPrime() {
for (factor = 2; factor < i; factor++) {
if (i % factor = 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
}
document.write(sum);
I am trying to check for the sum of all the prime numbers under 250. I am getting an error saying that i is invalid in the statement if (i % factor = 0)
I know was creating in the original for statement, but is there any way to reference it in the if statement?
Here is a simple way of looping through array and implementing the sieve of Eratosthenes...
You generate the array beginning with 2 as first prime, You sieve the array removing items by the remainder of prime using % === 0. The you loop through the remaining array by using the next prime until the last remaining prime is pushed to the prime arrays. Add all primes to get the Sum.
You can equally use this;
With the prime computation, have you considered using Sieve of Eratosthenes? This is a much more elegant way of determining primes, and, summing the result is simple.
(EDIT) With the updated algorithm, there are now two max involved:
You will have to validate this by actually checking the real count since there are two terminating conditions (1) we hit the limit of our sieve and cannot find any more primes, or (2) we actually found what we're looking for.
If you were to increase the number to numbers much greater than 250, than the Sieve no longer becomes viable as it would be consume great deals of memory. Anyhow, I think this all makes sense right? You really need to play with the Sieve yourself at this point than rely on my interpretation of it.
So i had to face a similar challenge and here is my solution, i hope you find it helpful:
Here's a pretty decent way to do it. It's not as advanced as the sieve but it's a decent starting point. NOTE: I'm using ES6 syntax.
i % factor === 0
Use
===
for comparison.=
is for assignment. Yeah I said triple equals. Type coercion is annoying.