2016-07-26 19 views
0

我已經看到一個在線測試任務,具有競爭性的編程挑戰(不能透露不幸地在哪裏)產生第N個斐波納契數的最後(最低有效)6位數字。我們如何才能達到最後O(logN)時間的第N個斐波納契數的6位數?

我已成功地拿出了以下解決方案:

#include <iostream> 
#include <cassert> 
#include <tuple> 

int solution(int N) 
{ 
    if(N == 0) return 0; 
    if(N == 1) return 1; 
    if(N == 2) return 1; 
    int a = 0; 
    int b = 1; 
    int c = 1; 

    for (int i = 3; i <= N; ++i) { 
    std::tie(a, b, c) = std::make_tuple(b, (a + b) % 1000000, (b + c) % 1000000); 
    } 
    return c; 
} 

int main() 
{ 
    assert(solution(8) == 21); 
    assert(solution(36) == 930352); 
    std::cout << solution(10000000) << std::endl; 
} 

不幸的是具有O(N)時間複雜度,並開始像在上線運行的投入相當緩慢:N> 10000000

任何人都知道O(logN)這可以實現嗎?

+2

想必,就像你可以得到*整個* [在O(log n)時間中的[第n個斐波那契數)一樣(http://stackoverflow.com/a/1525544/4892076) – jaggedSpire

+0

@jaggedSpire我認爲我們可以可能是dupe-tag。 – user4581301

+0

這些問題的註釋表明答案在某個數字上是錯誤的。 – West

回答