File tree Expand file tree Collapse file tree 2 files changed +15
-13
lines changed
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree 2 files changed +15
-13
lines changed Original file line number Diff line number Diff line change 11package com .thealgorithms .maths ;
22
33public 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}
Original file line number Diff line number Diff line change 55import org .junit .jupiter .api .Test ;
66
77public 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}
You can’t perform that action at this time.
0 commit comments