This is the second solution to find whether the given integer number is prime or not using a simple predicate and another core logic that no number is divisible by more than half of itself.
import java.util.Scanner;
import java.util.function.Predicate;
public class PrimeNumCheck {
public static void main(String[] args) {
System.out.println("OUTPUT:");
Scanner inpNum= new Scanner(System.in);
System.out.print("Enter an integer value for prime number check:");
int actualNum=inpNum.nextInt();
boolean isPrime=true;
//Define a basic predicate which checks reminder value
Predicate<Integer> reminderEqualsToZero = i -> (i==0);
//Initialize the highest boundary in the for loop
int upperBoundary = actualNum/2;
for(int num=2;num<=upperBoundary;num++) {
if (reminderEqualsToZero.test(actualNum%num)) {
isPrime=false;
System.out.println("The number "+ actualNum+ " is not prime");
break;
}
}
if (isPrime)
System.out.println("The number "+ actualNum +" is prime");
inpNum.close();
}
}
OUTPUT:
Enter an integer value for prime number check:641
The number 641 is prime

Leave a comment