What is a built-in function that finds the next largest prime in java?

Does the Java API provide a function that calculates the next largest prime number given input x?

+6
source share
6 answers

This would be a rather esoteric method, and not a very large candidate for inclusion in a common class library. You will need to write this yourself using test or sieve .

+5
source

Yes, there is no such function!

+4
source

There is BigInteger.nextProbablePrime() , which may come up if you work with large integers. Otherwise, you can write your own quite easily. Here is the one I prepared earlier:

 static long nextPrime(long previous) { if (previous < 2L) { return 2L; } if (previous == 2L) { return 3L; } long next = 0L; int increment = 0; switch ((int)(previous % 6L)) { case 0: next = previous + 1L; increment = 4; break; case 1: next = previous + 4L; increment = 2; break; case 2: next = previous + 3L; increment = 2; break; case 3: next = previous + 2L; increment = 2; break; case 4: next = previous + 1L; increment = 2; break; case 5: next = previous + 2L; increment = 4; break; } while (!isPrime(next)) { next += increment; increment = 6 - increment; // 2, 4 alternating } return next; } 

This uses wheel 2, 4 to skip multiple of 2 and 3. You will need a simple testing method:

 boolean isPrime(long toTest) { ... } 

which returns true if its parameter is simple, false otherwise.

+3
source

Java The java.math.BigInteger class contains the nextProbablePrime () method to verify the correctness of the 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()); } } 

Conclusion: 89 next prime number 83

For more information, see my blog:
http://javaexplorer03.blogspot.in/2016/05/generate-next-prime-of-number-in-java.html

+1
source
 public class nextprime { public static void main(String args[]) { int count = 0; int n = 17; for (int i = 2; i <= n / 2; i++) { if (n % i == 0) { count++; } } if (count == 0) { System.out.println("prime"); for (int p = n + 1; p >0; p++) { int y=0; for (int i = 2; i <= p / 2; i++) { if (p % i == 0) { y++; } } if(y==0) { System.out.println("Next prime "+p); break; } } } else { System.out.print("not prime"); } } 

}

0
source

Primes.nextPrime(int n) from Apache Commons Math is what you need.

0
source

Source: https://habr.com/ru/post/892518/


All Articles