【问题标题】:Finding the nth term of large Fibonacci numbers找到大斐波那契数的第 n 项
【发布时间】:2014-02-22 10:09:08
【问题描述】:

我必须编写一个程序,在其中给出第 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 个学期时,它开始放缓。

【问题讨论】:

  • 不递归重写。这就是减慢速度的原因。

标签: c++ recursion fibonacci


【解决方案1】:

第 479 个数字是 5696323922575865414847061494575945648081290145228607189038829076215134884313127297923138542545712321

即使在 long long 变量中也不适合。我建议您仅考虑数字的最低部分来实施它。您不需要存储完整的数字只是为了计算最后 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: %03d\n", searched);

    for(pos = 2; y != searched; pos++){
        tmp = x+y;
        x = y;
        y = tmp%1000;
    }

    pos--;
    printf("Found at position: %d\n", pos);

    num = (powl(PHI, pos) - powl(1-PHI, pos))/sqrt(5);
    printf("Approximated number %Le\n", num);

    while(num >= 10) num /= 10;

    printf("First digit: %d\n", (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

此代码首先计算我们要查找的数字在序列中的位置,然后使用可以逼近斐波那契数列的第 n 个数字的Binet's formula。由于我们只需要第一个数字,因此我们可以容忍近似误差。

【讨论】:

  • 我知道它是如何找到第 n 项的,但我认为它没有找到该序列的第一个数字,这是我需要找到的另一件事
猜你喜欢
  • 1970-01-01
  • 2021-09-03
  • 2015-04-17
  • 2022-12-10
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
相关资源
最近更新 更多