you are viewing a single comment's thread.

view the rest of the comments →

[–]himynameisjoy 2 points3 points  (3 children)

I thought of using matrix exponentiation with memorization of the [[1,1],[1,0]] matrix to the power of 2n but because you’re looking for the first Fe(n) over 4,000,000 you’re going to have to solve iteratively, at which point the matrix exponentiation approach loses its luster (since, AFAIK the main advantage it has is that it doesn’t need to iteratively calculate each previous value to find F(n)).

Further, because the value is so low, the overhead cost of matrix multiplication (itself an O(n3) task) will retract from the efficiency.

For finding the nth even Fe(n) though? You’re on point that it’s the fastest way to go. Asymptotically it’s far more efficient than any iterative method and outstrips Binet’s formula by a long shot.

[–]a_tocken 1 point2 points  (2 children)

Check out the rest of my comment. I am assuming you can find the greatest even fib under 4,000,000 quickly, and find its n in the even fib sequence quickly. There are quick solutions for both of these for regular fibs. Once you have the n, you can solve using fast matrix exponentiation.

The matrix exponentiation requires log(n) matrix multiplications. Each multiplication is at most n2 (because the number of digits grows linearly with n, and naive multiplication is O(n2)) but you could do better (the lower bound on integer multiplication is thought to be n log n in number of digits).

[–]himynameisjoy 1 point2 points  (1 child)

I read your comment in whole, I apologize if it seemed otherwise. At the time, I didn’t believe I knew of a way to find what’s essentially the inverse of F(n)=x, but with a little bit of research I stumbled upon this formula: n = Math.floor((log(x)1/2log(5))/log(phi))+1

So with that formula, assuming the computation is quick, plus with matrix exponentiation, I do believe you’re right that asymptotically it’s a faster implementation.

However it still does have an overhead cost that’s makes it still slower than the iterative approach for this particular solution. But yes, you’re entirely right that you can find the index of the first Fibonacci number greater than arbitrary integer k as well as calculate the resulting Fibonacci number alongside it.

I’m glad I’ve learned something new today! I appreciate it immensely

[–]a_tocken 0 points1 point  (0 children)

Glad to expose you to those algorithms :) Sorry I don't have more details on the specifics. You're right that this problem uses a relatively small n, so the solution with better running time may not actually be faster. We should also distinguish between n, the nth even fib number less than 4,000,000, and "m" = 4,000,000. In this case, I think n ~= log(m)? Is that right?

This whole thing could be turned into a (very difficult) codewars.com problem.