JavaAlgorithms/Maths/FactorialRecursion.java

27 lines
597 B
Java
Raw Normal View History

2019-10-29 12:40:39 +08:00
package Maths;
public class FactorialRecursion {
2020-10-24 18:23:28 +08:00
/* Driver Code */
public static void main(String[] args) {
assert factorial(0) == 1;
assert factorial(1) == 1;
assert factorial(2) == 2;
assert factorial(3) == 6;
assert factorial(5) == 120;
}
2019-10-29 12:40:39 +08:00
2020-10-24 18:23:28 +08:00
/**
* Recursive FactorialRecursion Method
*
* @param n The number to factorial
* @return The factorial of the number
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("number is negative");
2019-10-29 12:40:39 +08:00
}
2020-10-24 18:23:28 +08:00
return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
}
2019-10-29 12:40:39 +08:00
}