c++ - 如何找到由公式计算的非常大的数字的最后一位?

标签 c++ fibonacci

我有一个斐波那契数列问题,我想计算第 n 个斐波那契数列并想要它的最后一位数字(当我完成它时我得到的数字 % 10)。 n 将被给出并且可以达到 10^18。

unsigned long long int nthfib(long long int n) { 
    double phi = (1 + sqrt(5)) / 2; 
    return round(pow(phi, n-1) / sqrt(5));
}

上面的代码,对于大n,例如1024,给出的数字太大,我无法将它存储在变量中并找到它的 %10。

由于时间紧迫,我想要 O(1) 内的解决方案。

最佳答案

Fibonacci 数遵循一种模式,即最后一位数字每 60 个数字重复一次。参见 http://mathworld.wolfram.com/FibonacciNumber.html

The sequence of final digits in Fibonacci numbers repeats in cycles of 60. The last two digits repeat in 300, the last three in 1500, the last four in 15000, etc. The number of Fibonacci numbers between n and 2n is either 1 or 2 (Wells 1986, p. 65).

Wells, D. The Penguin Dictionary of Curious and Interesting Numbers. Middlesex, England: Penguin Books, pp. 61-67, 1986.

要在常数时间内得到第n个数字的最后一位,可以将前60个数字的最后一位计算到一个数组中,然后返回n % 60该数组中的第一个数字。

关于c++ - 如何找到由公式计算的非常大的数字的最后一位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821214/

相关文章:

clojure - 如何在 Clojure 中实现这种快速加倍斐波那契算法?

javascript - 我怎样才能改变我的reduce()来对数字求和,直到得到所要求的数字?

list - Haskell- 在列表中查找元素并返回其位置

Python func_dict 用于内存;其他有用的技巧?

C++:使用一对 (cpp_int, int) 整数作为 unordered_map 中的键(其中 cpp_int 是 boost 多精度整数)

c++ - 从派生范围调用函数

c++ - 我这里可以不使用线程同步吗?

c++ - 定义相对包含路径

c++ - 在 Qt C++ 项目中使用 Go

c# - 斐波那契数列偶数之和