Is there any algorithm to compute the nth fibonacci number in sub linear time?
相关问题
- Faster loop: foreach vs some (performance of jsper
- Why wrapping a function into a lambda potentially
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
相关文章
- What are the problems associated to Best First Sea
- ceil conterpart for Math.floorDiv in Java?
- Coin change DP solution to keep track of coins
- why 48 bit seed in util Random class?
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- DOM penalty of using html attributes
- Which is faster, pointer access or reference acces
Fixed point arithmetic is inaccurate. Jason's C# code gives incorrect answer for n = 71 (308061521170130 instead of 308061521170129) and beyond.
For correct answer, use a computational algebra system. Sympy is such a library for Python. There's an interactive console at http://live.sympy.org/ . Copy and paste this function
Then calculate
You might like to try inspecting
phi
.Here's a one-liner that computes F(n), using integers of size O(n), in O(log n) arithmetic operations:
Using integers of size O(n) is reasonable, since that's comparable to size of the answer.
To understand this, let phi be the golden ratio (the largest solution to x^2=x+1) and F(n) be the n'th Fibonacci number, where F(0)=0, F(1)=F(2)=1
Now, phi^n = F(n-1) + F(n)phi.
Also numbers of the form (a+b*phi), where a, b are integers are closed under multiplication.
Using this representation, one can compute phi^n in O(log n) integer operations using exponentiation by squaring. The result will be F(n-1)+F(n)phi, from which one can read off the n'th Fibonacci number.
Note that the majority of this code is a standard exponentiation-by-squaring function.
To get to the one-liner that starts this answer, one can note that representing phi by a large enough integer
X
, one can perform(a+b*phi)(c+d*phi)
as the integer operation(a+bX)(c+dX) modulo (X^2-X-1)
. Then thepow
function can be replaced by the standard Pythonpow
function (which conveniently includes a third argumentz
which calculates the result moduloz
. TheX
chosen is2<<i
.using R
If you want the exact number (which is a "bignum", rather than an int/float), then I'm afraid that
It's impossible!
As stated above, the formula for Fibonacci numbers is:
How many digits is
fib n
?Since the requested result is of O(n), it can't be calculated in less than O(n) time.
If you only want the lower digits of the answer, then it is possible to calculate in sub-linear time using the matrix exponentiation method.
see divide and conquer algorithm here
The link has pseudocode for the matrix exponentiation mentioned in some of the other answers for this question.
You can use the weird square rooty equation to get an exact answer. The reason is that the $\sqrt(5)$ falls out at the end, you just have to keep track of the coefficients with your own multiplication format.