mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-10 04:26:27 +08:00
Refactor factorial, add unit tests (#4266)
This commit is contained in:

committed by
GitHub

parent
cc9afea036
commit
f83008d80a
@ -1,15 +1,6 @@
|
|||||||
package com.thealgorithms.maths;
|
package com.thealgorithms.maths;
|
||||||
|
|
||||||
public class Factorial {
|
public class Factorial {
|
||||||
|
|
||||||
/* Driver Code */
|
|
||||||
public static void main(String[] args) {
|
|
||||||
assert factorial(0) == 1;
|
|
||||||
assert factorial(1) == 1;
|
|
||||||
assert factorial(5) == 120;
|
|
||||||
assert factorial(10) == 3628800;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculate factorial N using iteration
|
* Calculate factorial N using iteration
|
||||||
*
|
*
|
||||||
@ -18,11 +9,12 @@ public class Factorial {
|
|||||||
*/
|
*/
|
||||||
public static long factorial(int n) {
|
public static long factorial(int n) {
|
||||||
if (n < 0) {
|
if (n < 0) {
|
||||||
throw new IllegalArgumentException("number is negative");
|
throw new IllegalArgumentException("Input number cannot be negative");
|
||||||
}
|
}
|
||||||
long factorial = 1;
|
long factorial = 1;
|
||||||
for (int i = 1; i <= n; factorial *= i, ++i)
|
for (int i = 1; i <= n; ++i) {
|
||||||
;
|
factorial *= i;
|
||||||
|
}
|
||||||
return factorial;
|
return factorial;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,9 +5,19 @@ import static org.junit.jupiter.api.Assertions.*;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class FactorialTest {
|
public class FactorialTest {
|
||||||
|
private static final String EXCEPTION_MESSAGE = "Input number cannot be negative";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() {
|
public void testWhenInvalidInoutProvidedShouldThrowException() {
|
||||||
|
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1));
|
||||||
|
assertEquals(exception.getMessage(), EXCEPTION_MESSAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCorrectFactorialCalculation() {
|
||||||
|
assertEquals(1, Factorial.factorial(0));
|
||||||
|
assertEquals(1, Factorial.factorial(1));
|
||||||
assertEquals(120, Factorial.factorial(5));
|
assertEquals(120, Factorial.factorial(5));
|
||||||
|
assertEquals(3628800, Factorial.factorial(10));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user