Skip to content

Commit cce363d

Browse files
authored
Merge pull request TheAlgorithms#1251 from wendelllsc/patch-1
Using Try/catch and recursion
2 parents 4fef5da + e5ad1f2 commit cce363d

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Maths/Factorial.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,16 @@ public static void main(String[] args) { //main method
1919
* @return the factorial of {@code n}
2020
*/
2121
public static long factorial(int n) {
22-
if (n < 0) {
23-
throw new ArithmeticException("n < 0"); //Dont work with less than 0
24-
}
25-
long fac = 1;
26-
for (int i = 1; i <= n; ++i) {
27-
fac *= i;
28-
}
29-
return fac; //Return factorial
22+
// Using recursion
23+
try {
24+
if (n == 0) {
25+
return 1; // if n = 0, return factorial of n;
26+
}else {
27+
return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
28+
}
29+
}catch (ArithmeticException e) {
30+
System.out.println("Dont work with less than 0");
31+
}
32+
return n;
3033
}
3134
}

0 commit comments

Comments
 (0)