Refactor factorial, add unit tests (#4266)

This commit is contained in:
Albina Gimaletdinova
2023-07-28 22:02:04 +03:00
committed by GitHub
parent cc9afea036
commit f83008d80a
2 changed files with 15 additions and 13 deletions

View File

@ -1,15 +1,6 @@
package com.thealgorithms.maths;
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
*
@ -18,11 +9,12 @@ public class Factorial {
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("number is negative");
throw new IllegalArgumentException("Input number cannot be negative");
}
long factorial = 1;
for (int i = 1; i <= n; factorial *= i, ++i)
;
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
return factorial;
}
}