51.4k views
3 votes
Write a program to check if a given no is prime or composite and find it's factorial using consumer interface and predicate interface

Hint: Method accept(T t) to be used to print result.

Function Description

you have to implement the following functions in the class PrimeComposite_Factorial:

*primeOrComposite(int n)

*findFactorial(int n)

primeOrComposite:

The function should check if the given number 'n' is prime or Compositr using Predicate interface.

using Consumer interface, print ¨Prime¨ if 'n' is prime, ¨Composite¨if 'n' is composite, and ¨Neither Prime Nor Composite ¨ if 'n' is neither prime nor composite

findFactorial:

the function should find the factorial for the given number 'n'.

using Consumer Interface, print the factorial of the number in the next line

Constraints

o <= n <=20

-the only line of input consists of an integer, 'n'

sample input for custom testing

7

sample output

prime 5040

1 Answer

5 votes

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"
}
}
User Futureal
by
7.8k points