2014-02-17 64 views
1

的價值,我有以下代碼:打印出來的Java方法

public class GCD { 

public static int GCD(int m, int n){ 
    if (n==0) return m; 
    callCount(1); 
    return GCD(n,m%n); 
} 

public static int callCount(int n){ 
    int s = 0; 
    s+=n; 
    return s; 

} 

public static void main(String[] args) { 
    callCount(0); 
    System.out.println(GCD(10, 15)); 
    System.out.println(callCount()); 
    } 
} 

一旦GCD已經完成,我想打印出來GCD了多少次與方法callCount調用。我想我打算完全錯誤的callcount。

+0

是的。我試圖打印出通過GCD的次數,但我不確定正確的方法。 – Softey

+0

如果需要,你可以使用'BigInteger':https://stackoverflow.com/a/4009230/2591612 – Brian

回答

4

怎麼這樣呢?

public class GCD { 

private static int callCount = 0; 

public static int GCD(int m, int n){ 
    if (n==0) return m; 
    callCount++; 
    return GCD(n,m%n); 
} 


public static void main(String[] args) { 
    System.out.println(GCD(10, 15)); 
    System.out.println(callCount); 
} 
} 
+0

啊,這是一個很好的簡單方法。非常感謝 – Softey

-1

創建一個公共靜態變量計數,並在callCount()方法結束時增加它。 每當它被調用時,可見性將會增加,因此會顯示它被調用了多少次。

1

你可能想使s靜態INT,而不是將它聲明本地

public class GCD { 

    static int s = 0; 
+1

爲什麼要保持這個方法的計數,它的無用 – pedromss