File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/recursion Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .thealgorithms .recursion ;
2+
3+ /*
4+ The Factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
5+ It is defined as:
6+ n! = n × (n - 1) × (n - 2) × ... × 1
7+ with the base case:
8+ 0! = 1
9+
10+ Example:
11+ 5! = 5 × 4 × 3 × 2 × 1 = 120
12+ */
13+
14+ public final class Factorial {
15+
16+ private Factorial () {
17+ throw new UnsupportedOperationException ("Utility class" );
18+ }
19+
20+ /**
21+ * Computes the factorial of a non-negative integer using recursion.
22+ *
23+ * @param n the number for which factorial is to be calculated
24+ * @return factorial of n
25+ * @throws IllegalArgumentException if n is negative
26+ */
27+ public static long factorial (int n ) {
28+ if (n < 0 ) {
29+ throw new IllegalArgumentException ("Factorial is not defined for negative numbers." );
30+ }
31+ if (n == 0 || n == 1 ) {
32+ return 1 ;
33+ }
34+ return n * factorial (n - 1 );
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments