I’m trying to understand recursion with Java better and I’m doing a program which ist using iteration, head and tail recursion.It should count how many times does the different methods called. What should I add to the head and to the tail part to complete the program? Thank you in advance
public static void main(String[] args) {
}
private static int fibIt(int n) {
switch (n) {
case 0:
return 0;
case 1:
return 1;
}
int a = 0;
int b = 1;
for (int i = 2; i <= n; i++) {
b = a + b;
a = b - a;
}
return b;
}
private static int fibHr(int n) {
switch (n) {
case 0:
return 0;
case 1:
return 1;
default:
return fibHr(n - 1) + fibHr(n - 2);
}
}
private static int fibTr(int n) {
return fibTr(0, 1, n);
}
private static int fibTr(int a, int b, int n) {
switch (n) {
case 0:
return a;
case 1:
return b;
default:
return fibTr(b, a + b, n - 1);
}
}
>Solution :
You can convert each method to an instance method of a class which then holds the counter in a private field, with a getter to expose the value.
public class HeadRecursion {
private long counter = 0;
public int fib(int n) {
++counter;
switch (n) {
case 0:
return 0;
case 1:
return 1;
default:
return fibHr(n - 1) + fibHr(n - 2);
}
}
public long getCounter() { return count; }
}
Then you can instantiate your class, run your function and then get and output the counter:
public static void main() {
final var obj = new HeadRecursion();
obj.fib(10);
System.out.println(obj.getCounter());
}