计算斐波那契的递归调用次数

时间:2014-03-06 22:53:30

标签: java recursion

我有Fibonacci的递归方法。我正在尝试获取该方法的调用次数。当索引为3,4,5,6等时,计数输出应为3,5,9,15等。我的代码给了我错误的输出。也许我的for-loop正在影响它?请帮忙!

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);

      }
   }
}

1 个答案:

答案 0 :(得分:4)

正如评论中所建议的那样,您必须正确初始化并重置count

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
    }
}