gpt4 book ai didi

c++ - 打印第 n 个斐波那契数 [最多 1000 位]

转载 作者:行者123 更新时间:2023-11-30 18:31:52 25 4
gpt4 key购买 nike

如何在C/C++中计算第n个斐波那契数?斐波那契数列最多可包含 1000 位数字。我可以生成最多 2^64 (unsigned long long) 的数字。由于这是数量的限制,所以我猜测必须有其他方法来做到这一点 - 我不知道。

编辑:

此外,它必须在不使用任何外部库的情况下完成。

最佳答案

既然你还没有表明你已经开始,我会给出一些提示。

一千位数字很多。比 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 时的项和总和,速度会更快。

关于c++ - 打印第 n 个斐波那契数 [最多 1000 位],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19449994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com