In mathematics, the factorial of a positive integer n, denoted as n! , is the product of all positive integers less than or equal to n.

The factorial of n can be computed using the following rules.

Case I: If n is 1, then the factorial of n is 1.
Case II: If n is greater than 1, then the factorial of n is equal to n times the factorial of (n - 1).
The factorial method returns the factorial of n, as determined by case I and case II. Write the factorial method below. You are encouraged to implement this method recursively.

/** Precondition: n is between 1 and 12, inclusive.

* Returns the factorial of n, as described in part (a).

*/

public static int factorial(int n)

Respuesta :

Answer:

public static int factorial(int n) {

   

    if (n >= 1 && n <=12) {

           if (n==1)

               return 1;

           else

               return n * factorial(n-1);

    }

    else

        return -1;

}

Explanation:

Create a method called factorial that takes one parameter, n

Check if n is n is between 1 and 12. If it is between 1 and 12:

Check if it is 1. If it is 1, return 1. Otherwise, return n * function itself with parameter n-1.

If n is not between 1 and 12, return -1, indicating that the number is not in the required range.

For example:

n = 3  Is n==1, NO factorial(3) = n*factorial(2)

n = 2  Is n==1, NO factorial(2) = n*factorial(1)

n = 1  Is n==1, YES factorial(1) = 1.

Then factorial(2) = 2*1 = 2, factorial(3) = 3*2 = 6

RELAXING NOICE
Relax