Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/main/java/com/thealgorithms/recursion/Factorial.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.thealgorithms.recursion;

/*
The Factorial of a non-negative integer n is the product of all positive integers less than or
equal to n. It is defined as: n! = n × (n - 1) × (n - 2) × ... × 1 with the base case: 0! = 1

Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
*/

public final class Factorial {
private Factorial() {
throw new UnsupportedOperationException("Utility class");
}

/**
* Computes the factorial of a non-negative integer using recursion.
*
* @param n the number for which factorial is to be calculated
* @return factorial of n
* @throws IllegalArgumentException if n is negative
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
}
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/thealgorithms/recursion/FactorialTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.thealgorithms.recursion;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

public class FactorialTest {
@Test
public void testFactorialOfZero() {
assertEquals(1, Factorial.factorial(0));
}

@Test
public void testFactorialOfOne() {
assertEquals(1, Factorial.factorial(1));
}

@Test
public void testFactorialOfPositiveNumbers() {
assertEquals(120, Factorial.factorial(5));
assertEquals(720, Factorial.factorial(6));
assertEquals(5040, Factorial.factorial(7));
}

@Test
public void testFactorialOfTen() {
assertEquals(3628800, Factorial.factorial(10));
}

@Test
public void testNegativeNumberThrowsException() {
assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1));
}
}
Loading