11package com .thealgorithms .divideandconquer ;
22
3- import static org .junit .jupiter .api .Assertions .*;
4- import org .junit .jupiter .api .Test ;
3+ import static org .junit .jupiter .api .Assertions .assertDoesNotThrow ;
4+ import static org .junit .jupiter .api .Assertions .assertEquals ;
5+ import static org .junit .jupiter .api .Assertions .assertThrows ;
6+ import static org .junit .jupiter .api .Assertions .assertTrue ;
57
8+ import org .junit .jupiter .api .Test ;
69
710public class FactorialTest {
8- // --------------------------------------------------------
11+
12+ // --------------------------------------------------------
913 // SECTION 1: Basic Correctness Tests
1014 // --------------------------------------------------------
1115
@@ -21,9 +25,7 @@ void testFactorialOfZero() {
2125
2226 @ Test
2327 void testNegativeInputThrowsException () {
24- assertThrows (IllegalArgumentException .class , () -> {
25- Factorial .factorial (-5 );
26- });
28+ assertThrows (IllegalArgumentException .class , () -> Factorial .factorial (-5 ));
2729 }
2830
2931 // --------------------------------------------------------
@@ -45,16 +47,21 @@ void testLargeInputPerformance() {
4547 // --------------------------------------------------------
4648
4749 /**
48- * Local copy of the original recursive implementation
49- * used only for comparing performance inside the test.
50+ * Local copy of the original recursive implementation used only for comparing performance inside
51+ * the test.
5052 */
5153 private long recursiveFactorial (long n ) {
52- if (n < 0 ) throw new IllegalArgumentException ("Negative input not allowed" );
53- if (n == 0 || n == 1 ) return 1 ;
54- return n * recursiveFactorial (n - 1 );
54+ if (n < 0 ) {
55+ throw new IllegalArgumentException ("Negative input not allowed" );
56+ }
57+ if (n == 0 || n == 1 ) {
58+ return 1 ;
59+ } else {
60+ return n * recursiveFactorial (n - 1 );
61+ }
5562 }
5663
57- @ Test
64+ @ Test
5865 void testIterativeFasterThanRecursive () {
5966 long n = 18 ;
6067
@@ -67,11 +74,12 @@ void testIterativeFasterThanRecursive() {
6774 long endIter = System .nanoTime ();
6875
6976 assertEquals (recResult , iterResult );
70- assertTrue (endIter - startIter < endRec - startRec ,
77+ assertTrue (
78+ endIter - startIter < endRec - startRec ,
7179 "Iterative version should outperform recursive version" );
7280 }
7381
74- @ Test
82+ @ Test
7583 void testIterativeHandlesLargerInputsSafely () {
7684 assertDoesNotThrow (() -> Factorial .factorial (20 ));
7785 }
0 commit comments