Is this a good code?

Hi and welcome to the forum!

It is ok if your code doesn’t look as polished as the sample solutions. The first measure is if your code works, the second is if your code is readable, and the third measure is if your code is efficient.

I do think that you can improve your solution however.

First, your sum variable is called arr but is not an array.

You know a number is not prime if you find a divisor that is not the number itself. Why keep looking for divisors? That’s more work than you need to do.

Even numbers other than 2 can’t be prime, so why check even i?

If 2 is not a divisor, then you don’t need to check if other even j are divisors. Though you don’t need to check for even divisors if you aren’t checking the primality of even numbers.

You don’t need to check all the way to i for divisors. The largest possible prime divisor of a number is much smaller.

I hope these hints help you improve your code.

You could get an even more efficient solution if you look at a Seive of Eratoshenes based approach like I discussed here: JavaScript Performance Measurement & Variability

2 Likes