java - n > 46 Java 的斐波那契数列

标签 java fibonacci

我有以下代码,它提供了 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/

相关文章:

algorithm - 快速斐波那契递归

ruby - 斐波那契数列递归的解释

java - 如何在喷雾路由中将Java对象转换为Json

c# - 打印斐波那契数达 15,000 C#

java - Is n :1 observable:observer with generics possible in java?(观察者模式)

java - Java 泛型什么时候需要 <?扩展 T> 而不是 <T> 并且切换有什么缺点吗?

python - Python 中的递归、内存和可变默认参数

c++ - 递归斐波那契数列

java - 在jsp中调用java文件

java - 尝试将依赖项传递给 gradle.build 文件中的子项目时出现compile()错误