打印第 n 个斐波那契数 [最多 1000 位]
Print nth Fibonacci number [upto 1000 digits]
如何在 C/C++ 中计算第 n 个斐波那契数?斐波那契数最多可以包含 1000 位数字。我可以生成最多 2^64 的数字(无符号长长)。由于这是数字的限制,所以我猜一定有其他方法可以做到这一点 - 我不知道。
编辑:
此外,必须在不使用任何外部库的情况下完成。
我会给出一些提示,因为你还没有表明你已经开始了。
一千位数很多。 比 C 或 C++ 中的任何内置数字类型都多。
解决这个问题的一种方法是使用任意精度的数学库。 这将具有结构,基本上可以在您的数字中为您提供尽可能多的数字。
另一种方法是滚动自己的缓存和携带:
unsigned short int term1[1024]; // 1024 digits from 0-9
unsigned short int term2[1024]; // and another
unsigned short int sum[1024]; // the sum
addBigNumbers(&term1, &term2, &sum); // exercise for the reader
我希望addBigNumbers
的算法是这样的:
Start at the ones digit (index 0)
Add term1[0] and term2[0]
Replace sum[0] with the right digit of term1[0] + term2[0] (which is ... ?)
Keep track of the carry (how?) and use it in the next iteration (how?)
Repeat for each digit
现在,由于您正在计算斐波那契数列,您将能够重复使用这些大数字来获得序列中的下一项。 您可能会发现,不复制它们会更快,而只是更改哪些是术语,哪些是重复调用addBigNumbers
的总和。
您可以尝试对任意大的整数使用 GMP。
相关文章:
- 最多获取2个对象
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 计算 PI 最多 42 位小数
- 最多总和为'k'的子序列
- 从组件的 std::type_index 获取派生最多的类型
- 如何在C++中找到变量派生最多的子类?
- 初始化一个由 p 指向的新 INTSTK,它最多可以存储 m 个
- 访问随机图像像素的快速方法,最多一次
- 将最多 50 位数字的 2 个数字相乘
- 在 64 位整数内旋转(90°)位矩阵(最多 8x8 位)
- 将负数和正数相加,最多为 10^100000
- 选择前缀数量最多的索引
- 最多匹配n个字符
- C++是否有一个容器,每个类型最多存储一个对象
- 如何为包含最多N个元素的std::multiset调用最大数量分配
- 舍入 QDecDouble 值,精度最多为两个字符
- C++ 如何找出数组中最多的连续数字?
- 计算段落中出现次数最多的单词
- 打印第 n 个斐波那契数 [最多 1000 位]
- 如何在 C/C++ 中计算一个数字中的位数,最多 1000 位