find the nearest prime number in java
The closest prime can be greater or smaller than the passed input integer. If there are equi-distant
prime-numbers, print both.
Example:
Input#1: 32
Output#1: 31
Input#2: 30
Output#2: 29 31
Code::
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
find(n);
}
public static void find(int num) {
// greater number
int num1 = num + 1;
while (true) {
if (isPrime(num1)) {
break;
}
num1++;
}
// smaller
int num2 = num - 1;
while (num2 > 1) {
if (isPrime(num2)) {
break;
}
num2--;
}
// System.out.println(num1+" "+num2);
if (num2 == 1) {
System.out.println(num1);
} else if (num1 - num == num - num2) {
System.out.println(num2 + " " + num1);
} else if (num1 - num < num - num2) {
System.out.println(num1);
} else {
System.out.println(num2);
}
}
public static boolean isPrime(int n) {
for (int j = 2; j * j <= n; j++) {
if (n % j == 0) {
return false;
}
}
return true;
}
}
Comments
Post a Comment