Final answer:
A program can be written in Java using Predicate for checking if a number is prime or composite, and Consumer for printing the result. The primeOrComposite function uses Predicate, while findFactorial calculates the factorial of the number.
Step-by-step explanation:
A program to check if a given number is prime or composite and find its factorial using Java's functional interfaces can be implemented by using a Predicate interface for the prime check and a Consumer interface to print out the result. To determine if a number is prime, you can check whether it has any divisors other than 1 and itself. The factorial can be calculated using a simple loop.
Function Descriptions
- primeOrComposite(int n): Uses a Predicate<Integer> to return true if the number is composite (i.e., not prime).
- findFactorial(int n): Calculates the factorial of the number using a loop and outputs the result using a Consumer<Integer>.
Here's a simple skeleton code for reference:
import java.util.function.Predicate;
import java.util.function.Consumer;
public class PrimeComposite_Factorial {
Predicate<Integer> isComposite = n -> {
if(n < 2) return false;
for(int i = 2; i <= n / 2; i++) {
if(n % i == 0) return true;
}
return false;
};
Consumer<Integer> displayMessage = n -> {
if(n < 2) System.out.println("Neither Prime Nor Composite");
else System.out.println(isComposite.test(n) ? "Composite" : "Prime");
};
public void primeOrComposite(int n) {
displayMessage.accept(n);
}
public void findFactorial(int n) {
int result = 1;
for(int i = 2; i <= n; i++) {
result *= i;
}
System.out.println(result);
}
public static void main(String[] args) {
PrimeComposite_Factorial obj = new PrimeComposite_Factorial();
obj.primeOrComposite(7); // Should print "Prime"
obj.findFactorial(7); // Should print "4740"
}
}