I’m writing a code that finds prime numbers lesser than n,but the code gives me back 33 and 35 as prime numbers.I don’t understand why.Here’s my code:
function primeFinder(n) {
let prime = []
let index = 0
for (let i = 2; i <= n; i++) {
let root = Math.floor(Math.sqrt(i))
for (let j = 2; j <= root; j++) {
if (i % j == 0) {
i++
break
}
}
prime[index] = i
index++
}
return (prime)
}
console.log(primeFinder(35))
I tried to find the prime numbers but it doesn’t work as expected
3
Answers
Try something like this:
Your inner loop stops as soon as it finds a divisor of
i
, which means thati
is not prime. Then it incrementsi
and adds this to theprime
array. So for every non-prime value, it returnsi+1
as the next prime.You need to detect whether or not you make it all the way through the inner loop without finding a divisor, which means that the number is prime. Set a flag before the loop, update it when you find a divisor, and check the flag afterward.
When i is divisible with j, you just break the for statement and didn’t ignored adding i to the prime list.
That’s why you get all odd numbers as prime.
And for performance, your function will take much time if n is big enough.
Here’s the optimized code for getting all primes under n.
Remember, division takes much time in all programming languages and you should avoid them as you can.
In the code above, we don’t do any divisions.