Build your intuition. Fill in the missing part by typing it in.
The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n
. It is denoted by n!
.
For example, the factorial of __ is calculated as:
SNIPPET
1__________ = 5 * 4 * 3 * 2 * 1 = 120
To implement the factorial function using recursion, we can follow these steps:
- Define the base case: If
n
is 0 or 1, the factorial is 1. - Define the recursive case: If
n
is greater than 1, the factorial is calculated asn
multiplied by the factorial ofn - 1
. - Use recursion to call the factorial function with
n - 1
as the argument. - Return the result of
n
multiplied by the factorial ofn - 1
.
Let's fill in the blanks and complete the code:
TEXT/X-JAVA
1public class Factorial {
2 public static int factorial(int n) {
3 // Base case: If n is 0 or 1, return 1
4 if (n == 0 || n == 1) {
5 return 1;
6 }
7
8 // Recursive case: Return n * factorial(n - 1)
9 return n * factorial(n - 1);
10 }
11
12 public static void main(String[] args) {
13 // Example call to factorial for n = 5
14 int result = factorial(5);
15 System.out.println(result);
16 }
17}
The completed factorial function calculates the factorial of a given number n
using recursion. Try running the example code to see the factorial of 5 being calculated and printed to the console.
Write the missing line below.