mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-09 20:20:56 +08:00
Merge pull request #1251 from wendelllsc/patch-1
Using Try/catch and recursion
This commit is contained in:
@ -19,13 +19,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) {
|
||||||
long fac = 1;
|
return 1; // if n = 0, return factorial of n;
|
||||||
for (int i = 1; i <= n; ++i) {
|
}else {
|
||||||
fac *= i;
|
return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
|
||||||
}
|
}
|
||||||
return fac; //Return factorial
|
}catch (ArithmeticException e) {
|
||||||
|
System.out.println("Dont work with less than 0");
|
||||||
|
}
|
||||||
|
return n;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user