Whats the built in function that Finds next largest prime number in java?
Does the Java API provide a function which c开发者_JS百科omputes the next largest prime number given an input x?
That would be a pretty esoteric method, and not really a great candidate for inclusion in a general class library. You would need to write this yourself, using either a test or a sieve.
There is BigInteger.nextProbablePrime()
which may suit if you are working with large integers. Otherwise you can write your own easily enough. Here is 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 a 2, 4 wheel to skip over multiples of 2 and 3. You will need a prime testing method:
boolean isPrime(long toTest) { ... }
which returns true
if its parameter is prime, false
otherwise.
Yes, there really is no such function!
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
For more information, see my blog:
http://javaexplorer03.blogspot.in/2016/05/generate-next-prime-of-number-in-java.html
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");
}
}
}
Primes.nextPrime(int n)
from Apache Commons Math is what you need.
精彩评论