I have a Haskell solution to Project Euler Problem 2 which works fine for the four million limit, as well as for limits up to 10^100000, taking only a few seconds on my machine.
But for anything bigger, e.g. 10^1000000, the computation does not return in good time, if at all (have tried leaving it for a couple of minutes). What is the limiting factor here?
evenFibonacciSum :: Integer -> Integer
evenFibonacciSum limit =
foldl' (\t (_,b) -> t + b) 0 . takeWhile ((<=limit) . snd) . iterate doIteration $ (1,2) where
doIteration (a, b) = (twoAB - a, twoAB + b) where
twoAB = 2*(a + b)
The problem is that you are summing the (even) Fibonacci numbers. That means you have to calculate them all. But
So you are adding a lot of numbers of large size,
Θ(n)bits forF(n). For a limit of10^1000000, you need about 800000×2 additions of numbers larger than10^500000. In general, you needΘ(n)additions of numbers withΘ(n)bits.Adding numbers of
ddigits [in whatever base] is anO(d)operation. So your algorithm is quadratic in the exponent.To avoid that, find a closed formula for the sum
S(k)of the firstkeven Fibonacci numbers (hint: it’s a relatively easy formula involving one Fibonacci number), find the largestkso thatF(3*k) <= limit, and compute the sum using the formula and the algorithm to computeF(n)inO(log n)steps e.g. here.