Mark As Completed Discussion

Factorial

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 5 (5!) is calculated as:

SNIPPET
15! = 5 * 4 * 3 * 2 * 1 = 120

The factorial function is commonly implemented using recursion. The recursive definition of the factorial function is as follows:

  • Base case: If n is 0 or 1, the factorial is 1.
  • Recursive case: If n is greater than 1, the factorial is calculated as n multiplied by the factorial of n - 1.

Let's take a look at an example implementation of the factorial function in Java:

TEXT/X-JAVA
1public class Main {
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}

In this example, the factorial function takes an integer n as input and returns the factorial of n. The function uses recursion to calculate the factorial. The base case is when n is 0 or 1, in which case the function returns 1. The recursive case is when n is greater than 1. In this case, the function calculates the factorial of n by multiplying n with the factorial of n - 1. This recursive call continues until the base case is reached, resulting in the factorial of the original n.

Try running the example code to see the factorial of 5 being calculated and printed to the console.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

The factorial function is implemented using recursion in the example above. The base case is when n is 0 or 1, in which case the function returns 1. The recursive case is when n is greater than 1. In this case, the function calculates the factorial of n by multiplying n with the factorial of n - 1. This recursive call continues until the base case is reached, resulting in the factorial of the original n.

The example call to the factorial function with n = 5 will return the factorial of 5, which is 120.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment