Created
July 10, 2016 00:55
-
-
Save danielrobertson/5a7f3207a454e3496b610bb157b72707 to your computer and use it in GitHub Desktop.
Prime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.