我有以下代码,它提供了 n < 47 的正确值。
public static int fib(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm = 1;
else {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)
- Math.pow(1 - goldenRatio, n)) / Math.sqrt(5));
if (n % 2 == 1 && n < 45)
nthTerm++;
}
return nthTerm;
}
n > 46 的任何值都超出 int 范围。我如何调整这种方法以适用于 n > 46?
附注我知道 BigInteger,但不太擅长它,所以我也希望有一个使用 BigInteger 的示例。
最佳答案
您可以使用它将代码转换为 BigInteger。
package your.pack
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Created on 3/6/16.
*/
public class Fibonacci {
private static BigDecimal goldenRatio = new BigDecimal((1 + Math.sqrt(5)) / 2);
private static BigDecimal goldenRatioMin1 = goldenRatio.subtract(BigDecimal.ONE);
private static BigDecimal sqrt5 = new BigDecimal(Math.sqrt(5));
private static BigInteger fib(int n) {
BigInteger nthTerm = new BigInteger("0");
if (n == 2)
nthTerm = BigInteger.ONE;
else {
BigDecimal minResult = goldenRatio.pow(n).subtract(goldenRatioMin1.pow(n));
nthTerm = minResult.divide(sqrt5,0).toBigInteger();
if (n % 2 == 1 && n < 45){
nthTerm = nthTerm.add(BigInteger.ONE);
}
}
return nthTerm;
}
private static int fib2(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm = 1;
else {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)
- Math.pow(1 - goldenRatio, n)) / Math.sqrt(5));
if (n % 2 == 1 && n < 45)
nthTerm++;
}
return nthTerm;
}
public static void main(String []args){
System.out.println(
fib(47)
);
}
}
方法fib2是你的代码,fib是转换成BigInteger的。干杯
关于java - n > 46 Java 的斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822235/