Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fibonacci with 3 different recursion methods

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading