Even Fibonacci numbers
The other methods described work well, but I am partial to exact answers. So, here it is. First, note that the Fibbonacci sequence has a closed form
$$F_n = \frac{\Phi^n - (-\Phi)^{-n}}{\sqrt{5}}$$
where $\Phi$ is the GoldenRatio
. Also, as observed elsewhere, we are looking only at every third term, which gives the sum
$$\sum^k_{n = 1} \frac{\Phi^{3n} - (-\Phi)^{-3n}}{\sqrt{5}}$$
which is just the sum of two geometric series. So, after a few steps, this simplifies to
$$\frac{1}{\sqrt{5}} \left[ \Phi^3\frac{1 - (\Phi^3)^{k}}{1-\Phi^3} + \Phi^{-3}\frac{1 - (-\Phi^{-3})^{k}}{1 + \Phi^{-3}} \right]$$
where $k$ is the index of the highest even Fibbonacci number. To find $k$, we can reverse the sequence,
n[F_] := Floor[Log[F Sqrt[5]]/Log[GoldenRatio] + 1/2]
n[4000000]
(* 33 *)
So, $k = 11$. In code,
Clear[evenSum];
evenSum[(k_Integer)?Positive] :=
Round @ N[
With[
{phi = GoldenRatio^3, psi = (-GoldenRatio)^(-3)},
(1/Sqrt[5])*(phi*((1 - phi^k)/(1 - phi)) - psi*((1 - psi^k)/(1 - psi)))
],
Max[$MachinePrecision, 3 k] (* needed for accuracy *)
]
evenSum[11]
(* 4613732 *)
which is confirmed by
Total @ Fibonacci @ Range[3, 33, 3]
(* 4613732 *)
Edit: The above implementation of n
suffers round off problems for large numbers, for example n[9000]
gives 21, but Fibonacci[21]
is 10946. But, wikipedia gives a better choice
Clear[n2];
n2[fn_Integer?Positive] :=
Floor@N@Log[GoldenRatio, (fn Sqrt[5] + Sqrt[5 fn^2 - 4])/2]
n2[10945]
(* 20 *)
Straight iteration over the even valued Fibonacci numbers is fast.
fibSum[max_] := Module[
{tot, n, j},
tot = 0;
n = 0;
j = 3;
While[n = Fibonacci[j]; n <= max, j += 3; tot += n];
tot]
Or one can use matrix products. This seems to be about the same speed. It has the advantage of not requiring a built in Fibonacci
function.
fibSum2[max_] := Module[
{tot, n, fp, mat, mat3},
mat = {{0, 1}, {1, 1}};
tot = 0;
n = 0;
fp = mat.mat;
mat3 = mat.mat.mat;
While[n = fp[[2, 2]]; n <= max, fp = fp.mat3; tot += n];
tot]
These handle 10^10000 in slightly under a second on my desktop running Mathematica 9.0.1.
Here is a test for whether an integer is a Fibonacci number (a Fib detector?)
fibQ[n_] :=
With[{k =
Round[Log[GoldenRatio, N[n, 20 + Length[IntegerDigits[n]]]] +
Log[GoldenRatio, Sqrt[5]]]},
n == Fibonacci[k]]
Sum[Fibonacci[n],
{n, 3, InverseFunction[Fibonacci][4000000], 3}]
(* 4613732 *)