Skip to content

Instantly share code, notes, and snippets.

@RussellAndrewEdson
Last active August 29, 2015 14:13
Show Gist options
  • Save RussellAndrewEdson/3c2de500c70c5b8a8cf8 to your computer and use it in GitHub Desktop.
Save RussellAndrewEdson/3c2de500c70c5b8a8cf8 to your computer and use it in GitHub Desktop.
Exhaustive prime search: we check every single candidate.
import java.math.BigInteger;
/** Tests for a prime by checking every single candidate. */
public class ExhaustivePrimeSearch extends PrimalityTest {
@Override
public boolean isPrime(BigInteger n) {
// Only need to check numbers from 2 up to the square root.
BigInteger candidate = BigInteger.valueOf(2);
while ( (candidate.pow(2)).compareTo(n) == -1 ) {
if ( n.mod(candidate).compareTo(BigInteger.ZERO) == 0) {
// We have found a divisor here, so we don't have a prime.
return false;
}
candidate = candidate.add(BigInteger.ONE);
}
// If we got here, then no divisor was found; n is definitely prime.
return true;
}
public static void main(String[] args) {
(new ExhaustivePrimeSearch()).timedPrimeTest(
new BigInteger(args[0]) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment