1

I have the recursion method of Fibonacci. I am trying to get the number of calls for the method. When the index are 3, 4, 5, 6 and so on, the count output should be 3, 5, 9, 15 and so on. My code is giving me wrong outputs. Maybe my for-loop is affecting it? Please help!

import java.util.*;

public class RecursionCallsFib{
   private static int count;
   public static int rabbit(int n) {  //Fibinocci method 
      count++;
      if (n <= 2) {
         return 1;
      } 
      else  {// n > 2, so n-1 > 0 and n-2 > 0     

         return rabbit(n-1) + rabbit(n-2);
      }  
   }  

   public static void main(String [] args){
    System.out.println("Index" + "\t" + "Value" + "\t" + "Count");
      for(int p=1;p<=15;p++){ 
        System.out.println(p + "\t" + rabbit(p) + "\t" + count);

      }
   }
}
donfuxx
  • 11,277
  • 6
  • 44
  • 76
Matthew Luong
  • 19
  • 1
  • 4

1 Answers1

4

As proposed in the comment, you must initialize and reset count properly.

private static int count = 0; // <- initializing

// rabbit is ok

public static void main(String[] args) {
    System.out.println("Index" + "\t" + "Value" + "\t" + "Count");
    for (int p = 1; p <= 15; p++) {
        System.out.println(p + "\t" + rabbit(p) + "\t" + count);
        count = 0; // <- resetting
    }
}
exception1
  • 1,239
  • 8
  • 17