查找大型斐波那契数的第n项
Finding the nth term of large Fibonacci numbers
我必须编写一个程序,其中我获得了第n个学期的最后三位数。例如,第20项为6765,最后三位数字为" 765"。现在,我需要找到具有" 321"为最后三位数字的斐波那契序列的第一位数。
我在网上看,发现第n个学期是479,我编写的程序甚至无法达到那么高。我找不到任何具有比第100个学期更高的程序的人。
截至目前,他们无法找到高于100的术语吗?除了递归之外,还有其他想法以找到以" 321"结尾的数字的数字?
我的递归代码非常基本:
long long fibNum(long long nth)
{
if (nth == 1)
return 1;
else if (nth == 2)
return 1;
else
return fibNum(nth - 1) + fibNum(nth - 2);
}
到我进入第43个学期时,它开始放慢速度。
第479个数字是 5696323922575865414847061494575759459459459481290145222860718903829076290762151515134843484313127272979929799231385555555555555555555557112321
即使是长期变量也不适合。我建议您仅考虑到数字的最低部分。您不需要存储完整的数字即可计算最后3个数字,然后近似整个数字。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PHI 1.61803399
int main(int argc, char *argv[]){
int pos;
int x = 0, y = 1, tmp = 0;
long double num=0;
int searched = atoi(argv[1]);
printf("Looking for a fibonacci number ending with: %03dn", searched);
for(pos = 2; y != searched; pos++){
tmp = x+y;
x = y;
y = tmp%1000;
}
pos--;
printf("Found at position: %dn", pos);
num = (powl(PHI, pos) - powl(1-PHI, pos))/sqrt(5);
printf("Approximated number %Len", num);
while(num >= 10) num /= 10;
printf("First digit: %dn", (int)num);
return 0;
}
输出:
> ./finbonacci 321
Looking for a fibonacci number ending with: 321
Found at position: 479
Approximated number 5.696326e+99
First digit: 5
此代码首先计算我们在序列中寻找的数字的位置,而不是使用可以近似fibonacci序列的n数字的BINET公式。由于我们只需要第一个数字,因此我们可以容忍近似误差。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++中高效的大型稀疏块压缩线性方程
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 在大型 JSON 文件中查找文本
- 如何有效查找大型std :: map
- 在Visual Studio 2010中使用大型查找表的链接限制使用代码库的限制
- 查找大型斐波那契数的第n项
- 如何在visualstudio中快速搜索文件内容以查找大型代码库
- 查找大型boost::unordered_map的大小