Tuesday, 3 May 2016

Generate the next prime of a number in Java

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

import java.math.BigInteger;

public class NextPrime {

            public static void main(String[] args) {
                        int number = 83;
                        Long nextPrime = nextPrime(number);
                        System.out.println(nextPrime + " next prime to " + number);

            }

            /**
             * method to find next prime
             * @param number
             * @return boolean
             */
            private static Long nextPrime(int number) {
                        BigInteger bValue = BigInteger.valueOf(number);
                       
                        /**
                         * nextProbablePrime method used to generate next prime.
                         * */
                        bValue = bValue.nextProbablePrime();
                       
                        return Long.parseLong(bValue.toString());
            }
}

Output:
            89 next prime to 83

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...