0

I asked in a previous post about finding a closed form for: $$\sum_{i=0}^{n}F_{3i}$$ which is the sum of the even fibs less than or equal to the nth even fib. the great answersI got showed me a very simple solution, and a fast way to compute it! In case you're wondering what the solution is, it is this: $$\sum_{i=0}^{n}F_{3i}=\frac{F_{3n+2}-1}{2}$$

So know, as a follow up question, I'm asking if there is a quick way to find the index of the largest Fibonacci number less than a specific limit? If the answer isn't O(1), then would it be faster to find that n then compute the fib(3n+2) with matrix exponentiation, or would it be faster to use a brute force approach?

3uc1id
  • 378

1 Answers1

2

Well, for all $n\geq 0$, $F_n$ is the nearest integer to $\frac{1}{\sqrt 5}\left(\frac{1+\sqrt{5}}2\right)^n$. So if you want to find the largest $n$ such that $F_n<M$, you can compute:

$$n \approx \frac{\log (M\sqrt{5})}{\log \frac{1+\sqrt 5}2}$$

The size of $M$ and how close $M$ is to an $F_n$ affects how closely you need to approximate these various real numbers. This feels $O(1)$ for reasonable values of $M$. For example, when $M=1000000$, you get $n=30$, and $F_{30}=832040$.

The matrix technique I showed in the prior problem gives you an approach that lets you find $n$ and also find $F_n$ fairly quickly.

Basically, given the $A$ from my answer before, compute:

$$A, A^2, A^4, \dots, A^{2^k},\dots$$

by repeated squaring until you "get too far." So $F_{2^{k-1}}<M\leq F_{2^{k}}$. Now use a binary search for $2^{k-1}\leq n < 2^k$. You can do that quickly because you already computed $A^{2^i}$ for $i=0\dots,k-1$.

I'm not sure about the complexity of this process, but it is certainly not much worse than $O(\log M)$. It's hard to do better than that since you are adding and multiplying numbers with up to $\log M$ bits. You can probably find $n$ faster if you don't also need to find $F_n$.

Now, if you want the largest $F_{3k+2}<M$, you might have to take the resulting $A^n$ and multiply it by $A^{-1}$ or $A^{-2}$ to get the appropriate maximum in that case.

Thomas Andrews
  • 186,215
  • thanks again! You definitely get credit on any code I write up for this! My idea was to find the n quickly and decrement it by n%3, then compute $F_{n+2}$ with exponentiation by squaring. – 3uc1id Mar 07 '13 at 20:33