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.
2 parents 4fef5da + e5ad1f2 commit cce363dCopy full SHA for cce363d
Maths/Factorial.java
@@ -19,13 +19,16 @@ public static void main(String[] args) { //main method
19
* @return the factorial of {@code n}
20
*/
21
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
+ // 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) {
30
+ System.out.println("Dont work with less than 0");
31
32
+ return n;
33
}
34
0 commit comments