This exercise is reserved for pair programming in the live lab sessions.
Please skip it when doing the exercises individually.
We often want to know how many ways we arrange a set of objects. For example, given the string of letters “ABC”, how many different orderings are there? The answer is 6: “ABC”, “ACB”, “BAC”, “BCA”, “CAB”, “CBA”.
The study of permutations and combinations often involves the factorial() function. For example, the number of possible rearrangements of “ABC” would be
\[ N ! \text{ where } N = 3 \]The factorial function is defined as
\[ N! = N \times (N-1) \times (N-2) \times (N-3) \times \ldots \times 2 \times 1 \]For example,
\[ 7! = 7 \times 6 \times 5 \times 4 \times 3 \times 2 \times 1 \]If we look at the formula, and consider the following identities
\[ \begin{split} N! &= N \times (N-1) \times (N-2) \times (N-3) \times ... \times 2 \times 1 \\ (N-1)! &= (N-1) \times (N-2) \times (N-3) \times ... \times 2 \times 1\end{split} \]then we can write
\[ \begin{split}N! &= N \times (N-1)!\end{split} \]That is, if we can compute \( (N - 1)! \), then multiplying the result by \( N \) gives us \( N! \) This makes factorials an example of where we can use recursion in programming.
Write a class Factorial containing a method factorial() with the following signature:
public static int factorial(int N)
The factorial() method should make recursive calls to itself until it reaches a suitable stopping condition. In the definition of factorial, the base case for the recursion is given by \( 1! = 1 \). When your method factorial(1) is called, make sure it returns 1 to stop your program recursing forever.
For testing, it may be helpful to use the following main() method for developing, although it is not required that your code will have one.
public class Factorial { public static int factorial(int N) { // ADD CODE HERE } public static void main(String[] args) { System.out.print(" 2! (Should be: 2) returned: " + factorial(2) ); System.out.print(" 5! (Should be: 120) returned: " + factorial(5) ); System.out.print(" 10! (Should be: 3628800) returned: " + factorial(10) ); } }
An automated test has been created for this exercise: FactorialTest.java.