forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorialTest.java
More file actions
82 lines (66 loc) · 2.58 KB
/
FactorialTest.java
File metadata and controls
82 lines (66 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.thealgorithms.divideandconquer;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class FactorialTest {
// --------------------------------------------------------
// SECTION 1: Basic Correctness Tests
// --------------------------------------------------------
@Test
void testFactorialOfFive() {
assertEquals(120, Factorial.factorial(5));
}
@Test
void testFactorialOfZero() {
assertEquals(1, Factorial.factorial(0));
}
@Test
void testNegativeInputThrowsException() {
assertThrows(IllegalArgumentException.class, () -> { Factorial.factorial(-5); });
}
// --------------------------------------------------------
// SECTION 2: Analysis-Oriented Test (Performance Awareness)
// --------------------------------------------------------
@Test
void testLargeInputPerformance() {
long start = System.currentTimeMillis();
long result = Factorial.factorial(15);
long end = System.currentTimeMillis();
assertEquals(1307674368000L, result);
assertTrue((end - start) < 50, "Factorial(15) took too long to compute");
}
// --------------------------------------------------------
// SECTION 3: Algorithmic Improvement Demonstration
// --------------------------------------------------------
/**
* Local copy of the original recursive implementation
* used only for comparing performance inside the test.
*/
private long recursiveFactorial(long n) {
if (n < 0) {
throw new IllegalArgumentException("Negative input not allowed");
}
if (n == 0 || n == 1) {
return 1;
}
return n * recursiveFactorial(n - 1);
}
@Test
void testIterativeFasterThanRecursive() {
long n = 18;
long startRec = System.nanoTime();
long recResult = recursiveFactorial(n);
long endRec = System.nanoTime();
long startIter = System.nanoTime();
long iterResult = Factorial.factorial(n);
long endIter = System.nanoTime();
assertEquals(recResult, iterResult);
assertTrue(endIter - startIter < endRec - startRec, "Iterative version should outperform recursive version");
}
@Test
void testIterativeHandlesLargerInputsSafely() {
assertDoesNotThrow(() -> Factorial.factorial(20));
}
}