Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Last active October 14, 2017 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbonso/b8c453b0e5195f932eb46fe47fba2daf to your computer and use it in GitHub Desktop.
Save jsbonso/b8c453b0e5195f932eb46fe47fba2daf to your computer and use it in GitHub Desktop.
Java: Check if Number is a Prime Number
/**
* Checks the primality of the given number.
* Prime numbers can be used in password encryptions
* and cryptography.
*
* Basically, a prime number is:
* 1. A whole number which is greater than 1
* 2. And can only be divided evenly by 1
* and the number itself.
*
* @param number
* @author Jon Bonso
* @return boolean
*/
static boolean isPrimeV2(int number) {
if (number <= 1)
return false;
if (number == 2)
return true;
if ((number % 2) == 0)
return false;
for (int i=3; i < (number/2); i=i+2) {
if ( (number % i) == 0 )
return false;
}
return true;
}
/**
* Checks if the input is a prime number
* using BigInteger.isProbablePrime() method
* that implements Miller-Rabin primality tests
* @param input
* @author Jon Bonso
* @return
*/
static boolean isPrime(int input) {
BigInteger bigInt = BigInteger.valueOf(input);
// Sets the probability to 100 to make it a "certainty"
return bigInt.isProbablePrime(100);
}
public static void main(String... args) {
System.out.println( isPrime(1) );
System.out.println( isPrime(2) );
System.out.println( isPrime(3) );
System.out.println( isPrime(5) );
System.out.println( isPrime(9) );
System.out.println( isPrime(10) );
System.out.println( isPrime(11) );
System.out.println( isPrime(12) );
System.out.println( isPrime(13) );
System.out.println( isPrime(15) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment