Fibonacci Sum of Large Numbers(Only Last Digit to be Printed)

后端 未结 5 1979
死守一世寂寞
死守一世寂寞 2020-12-31 12:44

I have been trying to come out with a solution regarding the problem of finding the last digit of the sum of large n Fibonacci series. I have been able to pass several test

5条回答
  •  清歌不尽
    2020-12-31 13:23

    SOLVED IT

    Works on all range of inputs. It works on the following algorithm. The idea is to notice that the last digits of fibonacci numbers also occur in sequences of length 60 (from the previous problem: since pisano peiod of 10 is 60). Irrespective of how large n is, its last digit is going to have appeared somewhere within the sequence. Two Things apart from edge case of 10 as last digit.

    • Sum of nth Fibonacci series = F(n+2) -1
    • Then pisano period of module 10 = let n+2 mod (60) = m then find F(m) mod(10)-1

    Code as follows;

    #include 
    using namespace std;
    
    long long calc_fib(long long n) {
    
        n = (n+2)%60;
        int fib[n+1];
        fib[0]=0;
        fib[1]=1;
        int res = 1;
        for(int i = 2; i<=n;i++){
            fib[i] = (fib[i-1]%10 + fib[i-2]%10)%10;
            // res = res + fib[i];
        }
        // cout<> n;
    
        std::cout << calc_fib(n) << '\n';
        return 0;
    }
    

提交回复
热议问题