Skip to content
Merged
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
18 changes: 7 additions & 11 deletions src/main/java/com/thealgorithms/maths/Factorial.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
package com.thealgorithms.maths;

import java.math.BigInteger;

public final class Factorial {
private Factorial() {
}

/**
* Calculate factorial N using iteration
*
* @param n the number
* @return the factorial of {@code n}
*/
public static long factorial(int n) {
public static BigInteger factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input number cannot be negative");
}
long factorial = 1;
for (int i = 1; i <= n; ++i) {
factorial *= i;
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return factorial;
return result;
}
}
9 changes: 5 additions & 4 deletions src/test/java/com/thealgorithms/maths/FactorialTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.math.BigInteger;
import org.junit.jupiter.api.Test;

public class FactorialTest {
Expand All @@ -16,9 +17,9 @@ public void testWhenInvalidInoutProvidedShouldThrowException() {

@Test
public void testCorrectFactorialCalculation() {
assertEquals(1, Factorial.factorial(0));
assertEquals(1, Factorial.factorial(1));
assertEquals(120, Factorial.factorial(5));
assertEquals(3628800, Factorial.factorial(10));
assertEquals(BigInteger.ONE, Factorial.factorial(0));
assertEquals(BigInteger.ONE, Factorial.factorial(1));
assertEquals(BigInteger.valueOf(120), Factorial.factorial(5));
assertEquals(BigInteger.valueOf(3628800), Factorial.factorial(10));
}
}
Loading