c - Fibodigits - 计算斐波那契数位

标签 c fibonacci

我需要找到斐波那契数列的位数,直到 1000 位。

例如:1有1位,10有2位,100有3位...

斐波那契数列是这样开始的:0,1,2,3,5,8,13...

我必须插入 1000 并得到结果 4782。

我得到 4781 插入 524 见下文。我想插入 1000 并得到 4782。有没有可能的方法来获取我的堆栈长度?在 python 中我可以使用 len 函数,在 C 中它不起作用:)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int s) {
    int i = 1;
    int k = 1;
    int list[1000] = { 0, 1 };
    int fibo = 0;
    int s = -1;
    int divide = 0;
    while (i < 1500) {
        i++;
        fibo = list[i - 1] + list[i - 2];
        if (i == 1000) {
            break;
        } else {
            list[i] = fibo;
            //printf("%d\n", list[i]);
        }
    }

    while (s < 524) {
        s++;
        divide = 0;
        while (list[s] != 0) {
            divide = list[s] / 10;
            list[s] = divide;
            k++;
            if(divide == 0) {
                break;
            }
        } 
    }
    printf("%d\n", k);
}

最佳答案

这是一个使用近似值的快捷实现,即使对于非常小的数字也能很好地工作:

#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    int n;
    if (argc > 1) {
        n = strtol(argv[1], NULL, 0);
    } else {
        if (scanf("%d", &n) != 1)
            return 1;
    }
    double phi = (1.0 + sqrt(5.0)) / 2.0;
    printf("%g\n", ceil(n / log10(phi) - 3.0));
    return 0;
}

phi 是黄金比例。斐波那契数列很快收敛到黄金比例的几何数列。换句话说,fib(n) 大约为 pow(phi, n - 3)。将这个方程反演 10i 即可得到解。

关于c - Fibodigits - 计算斐波那契数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59240528/

相关文章:

c - 关于断言和中止陷阱 6

c - 如何更改Linux文件属性

c - 将一种类型的值移动到另一种类型是否违反严格别名?

c++ - 这段代码有什么问题?斐波那契数列

java - 不使用循环打印斐波那契数列

c: unsigned long long 仅在 HP-UX 上被分配了错误的值

prolog - 为什么这个 Prolog Fibonacci 函数会导致 "instantiation_error"?

linux - 递归斐波那契组装

prolog - 为什么我在 Prolog Fib/2 中的谓词总是说 "out of local stack"?

c - 使用 fscanf 解析带符号的数据