We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a45cbeb commit e5ad1f2Copy full SHA for e5ad1f2
Maths/Factorial.java
@@ -16,13 +16,16 @@ public static void main(String[] args) {
16
* @return the factorial of {@code n}
17
*/
18
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
+ // Using recursion
+ 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);
+ }
+ }catch (ArithmeticException e) {
27
+ System.out.println("Dont work with less than 0");
28
29
+ return n;
30
}
31
0 commit comments