mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-09 03:59:38 +08:00
Refactor factorial, add unit tests (#4266)
This commit is contained in:

committed by
GitHub

parent
cc9afea036
commit
f83008d80a
@ -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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user