File tree 2 files changed +15
-13
lines changed
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths
2 files changed +15
-13
lines changed Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .maths ;
2
2
3
3
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
-
13
4
/**
14
5
* Calculate factorial N using iteration
15
6
*
@@ -18,11 +9,12 @@ public static void main(String[] args) {
18
9
*/
19
10
public static long factorial (int n ) {
20
11
if (n < 0 ) {
21
- throw new IllegalArgumentException ("number is negative" );
12
+ throw new IllegalArgumentException ("Input number cannot be negative" );
22
13
}
23
14
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
+ }
26
18
return factorial ;
27
19
}
28
20
}
Original file line number Diff line number Diff line change 5
5
import org .junit .jupiter .api .Test ;
6
6
7
7
public class FactorialTest {
8
+ private static final String EXCEPTION_MESSAGE = "Input number cannot be negative" ;
8
9
9
10
@ 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 ));
11
20
assertEquals (120 , Factorial .factorial (5 ));
21
+ assertEquals (3628800 , Factorial .factorial (10 ));
12
22
}
13
23
}
You can’t perform that action at this time.
0 commit comments