查找大型斐波那契数的第n项

Finding the nth term of large Fibonacci numbers

本文关键字:大型 查找      更新时间:2023-10-16

我必须编写一个程序,其中我获得了第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公式。由于我们只需要第一个数字,因此我们可以容忍近似误差。