I have two questions: Is my programs code the most effective way at finding recursion or is there a much better and cleaner way? Why is the program showing 0 when I implement a number that depth is greater than 100? Shouldn't it show the number 1? Source code: package recursiveModule; public class RecursiveMethod { public static long calculateFactorial(int n, int depth) { if (depth > 100 || n <= 1) { return 1; } return n * calculateFactorial(n - 1, depth + 1); } public static void main(String[] args) { System.out.println("Factorial of 1 is " + RecursiveMethod.calculateFactorial(1, 0)); System.out.println("Factorial of 8 is " + RecursiveMethod.calculateFactorial(8, 0)); System.out.println("Factorial of 101 is " + RecursiveMethod.calculateFactorial(101, 0)); } }
I have two questions:
Is my programs code the most effective way at finding recursion or is there a much better and cleaner way?
Why is the
Source code:
package recursiveModule;
public class RecursiveMethod {
public static long calculateFactorial(int n, int depth) {
if (depth > 100 || n <= 1) {
return 1;
}
return n * calculateFactorial(n - 1, depth + 1);
}
public static void main(String[] args) {
System.out.println("Factorial of 1 is " + RecursiveMethod.calculateFactorial(1, 0));
System.out.println("Factorial of 8 is " + RecursiveMethod.calculateFactorial(8, 0));
System.out.println("Factorial of 101 is " + RecursiveMethod.calculateFactorial(101, 0));
}
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps