2010-11-17 55 views
0

嗨 我想調試這兩個代碼(斐波納契遞歸版本,另一個是斐波那契迭代版本)。我想要了解他們之間關於表現的區別。 但我不知道如何調試這些代碼,請幫助我謝謝。使用netbeans在java中調試代碼

斐波納契(遞歸):

public class Two{ 

    public static void main(String[] args){ 
     final Two obj = new Two(); 
     int sum = 0, i = 1; 
     obj.fibonacci(i); 
     while(obj.fibonacci(i) < 4000001){ 
      if(obj.fibonacci(i) % 2 == 0){ 
       sum += obj.fibonacci(i); 
      } 
      i++; 
     } 
     System.out.println(sum); 
    } 

    public int fibonacci(int n){ 
     if(n == 0){ 
      return -1; 
     } 
     if(n == 1){ 
      return 1; 
     } 
     if(n == 2){ 
      return 2; 
     } else{ 
      return fibonacci(n - 1) + fibonacci(n - 2); 

     } 
    } 
} 

斐波那契(迭代):

int sum = 0,a=1,b=1,c=a+b; 
    while (c<4000000){ 
     sum +=c; 
     a=c+b; 
     b=a+c; 
     c=a+b; 
    } 
    System.out.println(sum); 
+0

您正在使用:http://en.wikipedia.org/wiki/Plenken – Mot 2010-11-17 11:34:29

回答

2

其性能是被測添加這行代碼之前:

long start = System.currentTimeMillis(); 

代碼後打印出執行所需的時間:

System.out.println(System.currentTimeMillis() - start); 

如果你想知道計算的值更改這些行:

System.out.println(tempNumbers); 

} else { 
    return fibonacci(n - 1) + fibonacci(n - 2); 
} 

List<Integer> tempNumbers = new ArrayList<Integer>(); 
... 

} else { 
    int result = fibonacci(n - 1) + fibonacci(n - 2); 
    tempNumbers.add(result); 
    return result; 
} 

被測量打印出來的清單代碼後

+0

是你是對的,但我想獲得通過調用斐波那契按順序生成的整數。我怎樣才能看到這些值?即1,1,2,3,5 ... – user472221 2010-11-17 09:37:51

+2

存儲值以便稍後打印它們。在你的時間測量過程中不要使用'System.out.print()'。 – 2010-11-17 10:46:16