Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"isPrime" implementation is wrong #1

Closed
Stanko opened this issue Jun 30, 2017 · 1 comment
Closed

"isPrime" implementation is wrong #1

Stanko opened this issue Jun 30, 2017 · 1 comment

Comments

@Stanko
Copy link

Stanko commented Jun 30, 2017

Hello,
Thanks for putting this together, I was just browsing and noticed a bug in implementation of isPrime. It returns wrong results.

Try:

isPrime(9); // -> true
isPrime(21); // -> true
isPrime(25); // -> true

And none of these is prime. It will return true for any odd number, as you are skipping all of the odd number dividers (counter has a value of 2 + (n * 2)) on the line #17

  for (let i = 2; i < Math.ceil(Math.sqrt(n)); i += 2) {
    if (n % i === 0) {
      return false
    }
  }

You just need to increment by 1 not by 2.

Cheers!

@bcherny
Copy link
Owner

bcherny commented Jun 30, 2017

Good catch - thanks @Stanko.

bcherny added a commit that referenced this issue Jun 30, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants