This is the third solution to check whether the given integer number is prime or not. This solution uses the Lambda expression with single abstract method. The implementation is to check the divisibility of the given number, from 2 to till the square root of the given number.
//Define the functional interface with SAM 'Checkprime'
interface Checkprime {
public boolean prime(int tmp);
}
public class PrimenumberLambda {
public static void main(String[] args) {
System.out.println("OUTPUT:");
/* Define the Lambda expression for the functional interface 'Checkprime' */
Checkprime Cp = ((num) -> {
//Initialize the lower and upper boundary values in the for loop
int bvalToCheck = (int) Math.sqrt(num);
for(int i=2;i<=bvalToCheck;i++)
if(num%i==0)
return false;
return true;
});
System.out.println(41 +" is prime (true/false): "+Cp.prime(41));
System.out.println(341 +" is prime (true/false): "+Cp.prime(341));
System.out.println(441 +" is prime (true/false): "+Cp.prime(441));
System.out.println(541 +" is prime (true/false): "+Cp.prime(541));
}
}
OUTPUT:
41 is prime (true/false): true
341 is prime (true/false): false
441 is prime (true/false): false
541 is prime (true/false): true

Leave a comment