Last active
October 14, 2017 22:56
-
-
Save jsbonso/b8c453b0e5195f932eb46fe47fba2daf to your computer and use it in GitHub Desktop.
Java: Check if Number is a Prime Number
This file contains hidden or 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
/** | |
* 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