Fibonacci sequence for n > 46 Java

后端 未结 4 1941
旧时难觅i
旧时难觅i 2021-01-23 22:38

I have the following code which provides the correct values for n < 47.

public static int fib(int n) {
    int nthTerm = 0;
    if (n == 2)
        nthTerm =          


        
4条回答
  •  鱼传尺愫
    2021-01-23 23:23

    If you use long, you support perfectly the range over 1000; but if you want support all possible value then you need use BigInteger.

    A example use long:

    public static long fib(int n) 
    {
        long f0 = 1;
        long f1 = 1;
    
        long c = 2;
    
        while(c < n)
        {
            long tmp = f0+f1;
            f0 = f1;
            f1 = tmp;
            c++;
        }
    
        return f1;
    }
    

提交回复
热议问题