读书人

Exception in thread quot;mainquot; java.lan

发布时间: 2012-01-15 22:57:48 作者: rapoo

Exception in thread "main" java.lang.StackOverflowError .
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)

请问如何解决

[解决办法]
用递归出现这种情况很正常啊,而且,你的i非得那么大么?
[解决办法]
调大内存。。。。那其他没有办法了。。。

读书人网 >J2EE开发

热点推荐