Tuesday 3 May 2016

Check the Primality (prime) of the number in Java

Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.

isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.

Miller–Rabin primality algorithm is used to check primality in this method.

import java.math.BigInteger;

public class TestPrime {

      public static void main(String[] args) {
            int number = 83;
            boolean isPrime = testPrime(number);
            System.out.println(number + " is prime : " + isPrime);

      }

      /**
       * method to test primality
       * @param number
       * @return boolean
       */
      private static boolean testPrime(int number) {
            BigInteger bValue = BigInteger.valueOf(number);
           
            /**
             * isProbablePrime method used to check primality.
             * */
            boolean result = bValue.isProbablePrime(1);
           
            return result;
      }
}
Output: 83 is prime : true

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...