Skip to content

Commit 9729e56

Browse files
authored
Use BigInteger to prevent overflow in factorial calculation (#7358)
* Use BigInteger to prevent overflow in factorial calculation * chore: remove unnecessary comment * update * Fix: improve factorial implementation and formatting * test: final fix for FactorialTest logic and formatting * chore: final formatting and test fix for BigInteger * chore: final formatting and test fix for BigInteger
1 parent 635d54a commit 9729e56

File tree

2 files changed

+12
-15
lines changed

2 files changed

+12
-15
lines changed
Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,19 @@
11
package com.thealgorithms.maths;
22

3+
import java.math.BigInteger;
4+
35
public final class Factorial {
46
private Factorial() {
57
}
68

7-
/**
8-
* Calculate factorial N using iteration
9-
*
10-
* @param n the number
11-
* @return the factorial of {@code n}
12-
*/
13-
public static long factorial(int n) {
9+
public static BigInteger factorial(int n) {
1410
if (n < 0) {
1511
throw new IllegalArgumentException("Input number cannot be negative");
1612
}
17-
long factorial = 1;
18-
for (int i = 1; i <= n; ++i) {
19-
factorial *= i;
13+
BigInteger result = BigInteger.ONE;
14+
for (int i = 1; i <= n; i++) {
15+
result = result.multiply(BigInteger.valueOf(i));
2016
}
21-
return factorial;
17+
return result;
2218
}
2319
}

src/test/java/com/thealgorithms/maths/FactorialTest.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import static org.junit.jupiter.api.Assertions.assertEquals;
44
import static org.junit.jupiter.api.Assertions.assertThrows;
55

6+
import java.math.BigInteger;
67
import org.junit.jupiter.api.Test;
78

89
public class FactorialTest {
@@ -16,9 +17,9 @@ public void testWhenInvalidInoutProvidedShouldThrowException() {
1617

1718
@Test
1819
public void testCorrectFactorialCalculation() {
19-
assertEquals(1, Factorial.factorial(0));
20-
assertEquals(1, Factorial.factorial(1));
21-
assertEquals(120, Factorial.factorial(5));
22-
assertEquals(3628800, Factorial.factorial(10));
20+
assertEquals(BigInteger.ONE, Factorial.factorial(0));
21+
assertEquals(BigInteger.ONE, Factorial.factorial(1));
22+
assertEquals(BigInteger.valueOf(120), Factorial.factorial(5));
23+
assertEquals(BigInteger.valueOf(3628800), Factorial.factorial(10));
2324
}
2425
}

0 commit comments

Comments
 (0)