Using Try/catch and recursion

Adding try/catch and recursion to optimize the code
This commit is contained in:
Wendell Lucas
2020-03-17 23:05:27 -03:00
committed by GitHub
parent a45cbeb155
commit e5ad1f2ef0

View File

@ -16,13 +16,16 @@ public class Factorial {
* @return the factorial of {@code n} * @return the factorial of {@code n}
*/ */
public static long factorial(int n) { public static long factorial(int n) {
if (n < 0) { // Using recursion
throw new ArithmeticException("n < 0"); //Dont work with less than 0 try {
if (n == 0) {
return 1; // if n = 0, return factorial of n;
}else {
return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
} }
long fac = 1; }catch (ArithmeticException e) {
for (int i = 1; i <= n; ++i) { System.out.println("Dont work with less than 0");
fac *= i;
} }
return fac; //Return factorial return n;
} }
} }