I tried writing a function isDivisible
that returns false
if the number passed to it is divisible, determined by whether or not it can be divided evenly by a number from 2 to the its own square root. I tried to use that mark numbers as prime or not prime. But it seems I wrote it wrong as it marks all numbers aside from 6 as composite.
Without just giving me the solution, please help me with implementing the Sieve of Eratosthenes here. Using a working isDivisible
function. Thanks.
My code so far
function sumPrimes(num) {
const isDivisible = value => {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (value % i !== 0) {
return false;
}
}
return true;
}
const primes = [];
for (let i = 2; i <= num; i++) {
if (isDivisible(i)) {
continue;
} else {
primes.push(i);
}
}
console.log(primes)
}
sumPrimes(10);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 Edg/84.0.522.40
.
Challenge: Sum All Primes
Link to the challenge: