Skip to content

Commit e5ad1f2

Browse files
authored
Using Try/catch and recursion
Adding try/catch and recursion to optimize the code
1 parent a45cbeb commit e5ad1f2

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
@@ -16,13 +16,16 @@ public static void main(String[] args) {
1616
* @return the factorial of {@code n}
1717
*/
1818
public static long factorial(int n) {
19-
if (n < 0) {
20-
throw new ArithmeticException("n < 0"); //Dont work with less than 0
21-
}
22-
long fac = 1;
23-
for (int i = 1; i <= n; ++i) {
24-
fac *= i;
25-
}
26-
return fac; //Return factorial
19+
// Using recursion
20+
try {
21+
if (n == 0) {
22+
return 1; // if n = 0, return factorial of n;
23+
}else {
24+
return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
25+
}
26+
}catch (ArithmeticException e) {
27+
System.out.println("Dont work with less than 0");
28+
}
29+
return n;
2730
}
2831
}

0 commit comments

Comments
 (0)