How to calculate prime numbers.
public class PrimalityTest {
public static void main(String[] args) {
long nearest = findNearest(124981242424L);
System.out.println(nearest);
long[] primes = nextPrimes(124981242424L, 10);
System.out.println("Next 10 primes: ");
for (int i = 0; i < primes.length; i++) {
System.out.print(primes[i] + ",");
}
}
private static long[] nextPrimes(long num, final int count) {
long[] primes = new long[count];
int localCount = 0;
for (long number = num;; number++) {
if (isPrime(number)) {
primes[localCount++] = number;
if (localCount == count)
break;
}
}
return primes;
}
private static long findNearest(long num) {
long nearestLarger = -1;
for (long num2 = num;; num2++) {
if (isPrime(num2)) {
nearestLarger = num2;
break;
}
}
long nearestSmaller = -1;
for (long num2 = num;; num2--) {
if (isPrime(num2)) {
nearestSmaller = num2;
break;
}
}
if (nearestLarger - num > num - nearestSmaller) {
return nearestSmaller;
}
return nearestLarger;
}
public static boolean isPrime(final long num2) {
if (num2 <= 3)
return true;
if ((num2 & 1) == 0)// check divisibility by 2
return false;
double sqrt = Math.sqrt(num2);
for (long i = 3; i <= sqrt; i += 2)
if (num2 % i == 0)
return false;
return true;
}
}
In Maple:
. x:= 124981242424:
to 10 do x:= nextprime(x) end do;