I have two recursive methods in Java but I want to also implement a test class to see if both of them perform how can I do that? Method 1: Non Tail Recursive public class NonTailRecursiveFactorial { public static long factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { for (int i = 0; i <= 10; i++) { System.out.println(i + "! = " + factorial(i)); } } } Method 2: Tail Recursive Method public class TailRecursiveFactorial { public static long factorial(int n) { return factorial(n, 1); } private static long factorial(int n, long accumulator) { if (n == 0) { return accumulator; } return factorial(n - 1, accumulator * n); } public static void main(String[] args) { for (int i = 0; i <= 10; i++) { System.out.println(i + "! = " + factorial(i)); } }
I have two recursive methods in Java but I want to also implement a test class to see if both of them perform how can I do that?
Method 1: Non Tail Recursive
public class NonTailRecursiveFactorial {
public static long factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.println(i + "! = " + factorial(i));
}
}
}
Method 2: Tail Recursive Method
public class TailRecursiveFactorial {
public static long factorial(int n) {
return factorial(n, 1);
}
private static long factorial(int n, long accumulator) {
if (n == 0) {
return accumulator;
}
return factorial(n - 1, accumulator * n);
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.println(i + "! = " + factorial(i));
}
}
Step by step
Solved in 3 steps with 1 images