我正在尝试使用递归和BigInteger
类将Lucas系列转换为代码,但是我在设置基本情况时遇到了问题。这段代码正确地输出了Fibonacci序列,但是我试图分别获得起始值N(0)和N(1)分别为2和1的所有内容都完全失败了。我搜索了帮助文件,但我发现没有使用BigIntegers
完成它,我需要这样做,因为我打算远远超过int
限制。
import java.math.BigInteger;
public class LucasSeries {
private static BigInteger TWO = BigInteger.valueOf(2);
public static BigInteger fibonacci(BigInteger number) {
if (number.equals(BigInteger.ZERO) || number.equals(BigInteger.ONE)) {
return number;
} else {
return fibonacci(number.subtract(BigInteger.ONE)).add(fibonacci(number.subtract(TWO)));
}
}
public static void main(String[] args) {
for (int counter = 0; counter <= 30; counter++) {
System.out.printf("Lucas of %d is: %d%n", counter,
fibonacci(BigInteger.valueOf(counter)));
}
}
}
答案 0 :(得分:3)
有两个基本案例N(0)
和N(1)
。你可以组合这些,但如果你单独处理它们,代码会更紧密地匹配the series definition,如:
public static BigInteger fibonacci(BigInteger number) {
if (number.equals(BigInteger.ZERO))
return TWO;
if(number.equals(BigInteger.ONE))
return BigInteger.ONE;
return fibonacci(number.subtract(BigInteger.ONE)).add(
fibonacci(number.subtract(TWO)));
}
它产生以下输出:
Lucas of 0 is: 2
Lucas of 1 is: 1
Lucas of 2 is: 3
Lucas of 3 is: 4
Lucas of 4 is: 7
Lucas of 5 is: 11
Lucas of 6 is: 18
Lucas of 7 is: 29
Lucas of 8 is: 47
// Remainer omitted
答案 1 :(得分:2)
而不是
if (number.equals(BigInteger.ZERO) || number.equals(BigInteger.ONE))
return number;
返回
if (number.equals(BigInteger.ZERO) || number.equals(BigInteger.ONE)) {
return TWO.subtract(number);
全部。