我们如何在O(logN)时间内实现第N个Fibonacci数的最后6位

How can we achieve last e.g. 6 digits of of Nth Fibonacci number in O(logN) time?

本文关键字:Fibonacci 6位 最后 实现 时间 logN 我们      更新时间:2023-10-16

我在一个在线测试中看到了一项任务,该任务具有竞争性的编程挑战(不幸的是,无法透露在哪里),以产生第N个Fibonacci数的最后(最低有效)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;
}

不幸的是,它具有CCD_ 1的时间复杂性,并且对于最后一行中的输入开始运行得相当慢:N>10000000。

有人知道如何在O(logN)中实现这一点吗?

有一种算法使用Q矩阵计算第n个Fibonacci数需要O(log_n)时间。你可以看看http://kukuruku.co/hub/algorithms/the-nth-fibonacci-number-in-olog-n,您所需要的唯一更改是确保它只产生最后6位数字。