2019-09-28 11:15:22 +08:00
|
|
|
package Maths;
|
|
|
|
|
|
|
|
public class Factorial {
|
|
|
|
|
2020-08-16 19:58:48 +08:00
|
|
|
/* Driver Code */
|
|
|
|
public static void main(String[] args) {
|
|
|
|
assert factorial(0) == 1;
|
|
|
|
assert factorial(1) == 1;
|
|
|
|
assert factorial(5) == 120;
|
|
|
|
assert factorial(10) == 3628800;
|
|
|
|
}
|
2019-12-11 12:35:54 +08:00
|
|
|
|
2019-09-28 11:15:22 +08:00
|
|
|
/**
|
2020-08-16 19:58:48 +08:00
|
|
|
* Calculate factorial N using iteration
|
2019-09-28 11:15:22 +08:00
|
|
|
*
|
|
|
|
* @param n the number
|
|
|
|
* @return the factorial of {@code n}
|
|
|
|
*/
|
|
|
|
public static long factorial(int n) {
|
2020-08-16 19:58:48 +08:00
|
|
|
if (n < 0) {
|
|
|
|
throw new IllegalArgumentException("number is negative");
|
|
|
|
}
|
|
|
|
long factorial = 1;
|
|
|
|
for (int i = 1; i <= n; factorial *= i, ++i) ;
|
|
|
|
return factorial;
|
2019-09-28 11:15:22 +08:00
|
|
|
}
|
|
|
|
}
|