我们如何在O(logN)时间内实现第N个Fibonacci数的最后6位
How can we achieve last e.g. 6 digits of of Nth Fibonacci number in O(logN) time?
我在一个在线测试中看到了一项任务,该任务具有竞争性的编程挑战(不幸的是,无法透露在哪里),以产生第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位数字。
相关文章:
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- C / C++ 移位/偏移/向左或向右移动位图?
- 对字符串进行位操作
- 如何在24位SDL_Surface上设置像素的颜色
- 将浮动的heightmap数组导出为16位原始值
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- C++Union/Struct位域的实现和可移植性
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 将按位if条件转换为普通if条件
- 对字符数组中的元素执行逐位操作
- 将位字段导出到数组
- 将应用程序从32位移植到64位时出现问题
- 逐位操作的隐式类型转换
- 位阵列上的快速AND运算
- 64位机器上的C++内存对齐
- 一位朋友将模板函数缩写为clang和gcc
- 宽度为奇数的16位纹理为片状
- 如何打印boost多精度128位无符号整数
- 我们如何在O(logN)时间内实现第N个Fibonacci数的最后6位