Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.thealgorithms.recursion;

/*
* Factorial of a number n is the product of all positive integers less than
* or equal to n.
*
* n! = n × (n - 1) × (n - 2) × ... × 1
*
* Examples:
* 0! = 1
* 1! = 1
* 5! = 120
*/

public final class FactorialRecursion {

private FactorialRecursion() {
throw new UnsupportedOperationException("Utility class");
}

/**
* Computes the factorial of a non-negative integer using recursion.
*
* @param n the number whose factorial is to be computed
* @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 <= 1) {
return 1;
}
return n * factorial(n - 1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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;

class FactorialRecursionTest {

@Test
void testFactorialOfZero() {
assertEquals(1, FactorialRecursion.factorial(0));
}

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

@Test
void testFactorialOfPositiveNumber() {
assertEquals(120, FactorialRecursion.factorial(5));
}

@Test
void testFactorialOfLargerNumber() {
assertEquals(3628800, FactorialRecursion.factorial(10));
}

@Test
void testFactorialOfNegativeNumber() {
assertThrows(IllegalArgumentException.class, () -> FactorialRecursion.factorial(-1));
}
}