Skip to content

Commit f83008d

Browse files
authored
Refactor factorial, add unit tests (#4266)
1 parent cc9afea commit f83008d

File tree

2 files changed

+15
-13
lines changed

2 files changed

+15
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
11
package com.thealgorithms.maths;
22

33
public class Factorial {
4-
5-
/* Driver Code */
6-
public static void main(String[] args) {
7-
assert factorial(0) == 1;
8-
assert factorial(1) == 1;
9-
assert factorial(5) == 120;
10-
assert factorial(10) == 3628800;
11-
}
12-
134
/**
145
* Calculate factorial N using iteration
156
*
@@ -18,11 +9,12 @@ public static void main(String[] args) {
189
*/
1910
public static long factorial(int n) {
2011
if (n < 0) {
21-
throw new IllegalArgumentException("number is negative");
12+
throw new IllegalArgumentException("Input number cannot be negative");
2213
}
2314
long factorial = 1;
24-
for (int i = 1; i <= n; factorial *= i, ++i)
25-
;
15+
for (int i = 1; i <= n; ++i) {
16+
factorial *= i;
17+
}
2618
return factorial;
2719
}
2820
}

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

+11-1
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,19 @@
55
import org.junit.jupiter.api.Test;
66

77
public class FactorialTest {
8+
private static final String EXCEPTION_MESSAGE = "Input number cannot be negative";
89

910
@Test
10-
public void test() {
11+
public void testWhenInvalidInoutProvidedShouldThrowException() {
12+
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1));
13+
assertEquals(exception.getMessage(), EXCEPTION_MESSAGE);
14+
}
15+
16+
@Test
17+
public void testCorrectFactorialCalculation() {
18+
assertEquals(1, Factorial.factorial(0));
19+
assertEquals(1, Factorial.factorial(1));
1120
assertEquals(120, Factorial.factorial(5));
21+
assertEquals(3628800, Factorial.factorial(10));
1222
}
1323
}

0 commit comments

Comments
 (0)