gpt4 book ai didi

java - 如何编写一个函数来实现欧几里得算法来计算最大公约数(m,n)?

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:42 25 4
gpt4 key购买 nike

我正在尝试将 gcd() 函数添加到 NumericFunctions 类,并在 main 中包含代码来计算 gcd(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() 方法中的以下更正:

public static int gcd (int n, int m) {
if ((n % m) == 0)
return m; // <-- first correction
else
return gcd(m, n % m); // <-- second correction
}

关于java - 如何编写一个函数来实现欧几里得算法来计算最大公约数(m,n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com