1
我試圖將gcd()
函數添加到NumericFunctions類中,並在主要代碼中包含代碼以計算gcd(m,n)
。如何編寫一個實現歐幾里得計算最大公約數(m,n)的算法的函數?
不過,我不斷收到一個錯誤:
Exception in thread "main" java.lang.StackOverflowError
at NumericFunctions.gcd(NumericFunctions.java:14)
的源代碼:
public class NumericFunctions {
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static int gcd (int n, int m) {
if ((m % n) == 0)
return n;
else
return gcd(n, m % n);
}
public static void main(String[] args) {
for (int n = 1; n <= 10; n++)
for (int m = 1; m <= 10; m++){
System.out.println(gcd(n,m));
System.out.println(" ");
System.out.println(factorial(n));
}
}
}
你爲什麼不加一些調試到'gcd'並觀察傳遞給它的值? –