본문 바로가기

problem solving/Project Euler in Haskell

ProjectEuler Problem 2 - Even Fibonacci numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


The sequence of fibonacci numbers is defined as follow:


Writing it in Haskell is not that difficult:


Getting fibonacci numbers until it exceeds 4 million using takeWhile builtin function:

Greate! It works!! ..Uhh Hmmm... but it takes looong time..


Let's make memoization take part in exploting Haskell's lazy evaluation.

Yay!! It also work!! and It's fast like the Flash. What makes it faster is that the new version is not recursively calling fibs function to get already calculated value. fibs is function that returns list of fibonacci numbers and while calculating kth number, (k-1)th and (k-2)th numbers are already ready in the list so it is not necessary to call the function again. Just get that value from list.


Here is another magic:

Pretty cool!!


Now filter only even numbers using bultin filter function:


The answer is sum of the list:


in Python