Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 10, 2016 00:55
Show Gist options
  • Save danielrobertson/5a7f3207a454e3496b610bb157b72707 to your computer and use it in GitHub Desktop.
Save danielrobertson/5a7f3207a454e3496b610bb157b72707 to your computer and use it in GitHub Desktop.
Prime
boolean isPrime(int n) {
if(n < 2) return false;
for(int i = 2; i <= Math.sqrt(n); ++i) {
if(n % i == 0) return false;
}
return true;
}
@danielrobertson
Copy link
Author

The square root of n is sufficient because, for every number a which divides n evenly, there is a complement b, where a *b = n. I fa > sqrt(n), then b < sqrt(n) (since(sqrt(n))^2 = n).We therefore don't need a to check n's primality, since we would have already checked with b.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment