【发布时间】:2017-05-08 03:36:53
【问题描述】:
我正在尝试解决 java 中的项目 euler 25 问题,因为我需要一些东西来存储 10000 位数字,所以我正在使用 BigInteger 类。
所以我正在使用 BigIntegers 处理一些递归斐波那契序列,我正在尝试转换此代码:
public int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
来自此链接:Java recursive Fibonacci sequence
到相同的代码,但使用 BigIntegers。
所以,这就是我目前所拥有的:
public static BigInteger fibonacci(BigInteger index) {
if (index.compareTo(BigInteger.ZERO) == 0)
return BigInteger.ZERO;
else if (index.compareTo(BigInteger.valueOf(1)) == 1)
return BigInteger.ONE;
else
return fibonacci(index.subtract(BigInteger.ONE)).add(fibonacci(index.subtract(BigInteger.valueOf(2))));
}
public static int numberOfDigits(BigInteger fibonacci) {
return Integer.valueOf(fibonacci.toString().length());
}
public static void main(String[] args) {
long startTime = System.nanoTime();
for (BigInteger i = new BigInteger("1"); numberOfDigits(fibonacci(i)) <= 1000; i = i.add(BigInteger.ONE))
System.out.println(" " + i + " - " + fibonacci(i) + " - " + numberOfDigits(fibonacci(i)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Duration: " + duration/1000000 + " ms");
}
当我运行它时,我得到一个StackOverFlowError,像这样:
Exception in thread "main" java.lang.StackOverflowError
at java.math.BigInteger.subtract(BigInteger.java:1423)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
at Problem25Part2.fibonacci(Problem25Part2.java:19)
我想它会重复 1000 次。 好吧,我不知道出了什么问题,所以请你们帮帮我吗?谢谢!
【问题讨论】:
-
只需将程序转换为非递归形式即可。此外,使用 DP 将使该程序更快。正如
StackOverflowError所指出的那样,递归绝对不是这里的方法。 -
你不应该使用蛮力来解决项目欧拉问题。为什么使用 BigIntegers ?这个问题的重点不是大数,而是找到一种使计算时间可以接受的方法。多想想一种限制计算次数的有效方法,你就不需要任何花哨的类了:)
-
谢谢你们。认为递归更快,但我现在正在运行它,我看到它的方式更慢。谢谢!