Exception in thread "main" java.lang.StackOverflowError .

牛A_牛C 牛A_牛C 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
package 折半递归非递归;


public class RecursiveTest {
/** * 递归实现 * * @param n * @return */
public static double recursive(long n) {
if (n == 1) {
return Math.log(1);
}
else {
return Math.log(n) + recursive(n - 1);
}
}
/** * 非递归实现 * * @param n * @return */
public static double directly(long n) {
double result = 0;
for (int i = 1; i <= n; i++) {
result += Math.log(i);
}
return result;
}
public static void main(String[] args) {
int i = 5000000;

long test = System.nanoTime();
long start1 = System.nanoTime();
double r1 = recursive(i);
long end1 = System.nanoTime();
long start2 = System.nanoTime();
double r2 = directly(i);
long end2 = System.nanoTime();
System.out.println("recursive result:" + r1);
System.out.println("recursive time used:" + (end1 - start1));
System.out.println("non-recursive result:" + r2);
System.out.println("non-recursive time used:" + (end2 - start2));
}
}

运行后JAVA控制台输出:

Exception in thread "main" java.lang.StackOverflowError
at 折半递归非递归.RecursiveTest.recursive(RecursiveTest.java:11)
at 折半递归非递归.RecursiveTest.recursive(RecursiveTest.java:11)
at 折半递归非递归.RecursiveTest.recursive(RecursiveTest.java:11)

请问如何解决
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
牛A_牛C
Java EE 67,535 成员 225,843 内容