## Project Euler Problem 2

I will provide a solution for problem 2 in Scala. I think I will mark each solution moving forward as being just a solution. I have received feedback that someone can find this and learn bad style or not learn the language properly. I don’t want that to happen and you have been warned. The problem details are:

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.

For this problem I was able to pick up the concept of using a Stream. Its similar to a list, Daily Scala has a great explanation of the difference.

A Scala List basically consists of the head element and the rest of the list. A Scala Stream is the head of the stream and a function that can construct the rest of the Stream. It is a bit more than this because each element is evaluated only once and stored in memory for future evaluations. That should be more clear after some examples.

And now to the solution.

1 2 3 4 5 6 | object Euler002 { def main(args: Array[String]) { def fib(a:Int=1, b:Int=2):Stream[Int] = Stream.cons(a, fib(b, a+b)) println(fib().filter(_%2==0).takeWhile(_<4000000).sum) } } |

My solution is pretty straightforward. I define a fib method that take two arguments with default values. It returns a Stream of **Int**egers. The method definition **cons**tructs a Stream making a recursive call to itself. This will happen until we get to 4 million for everyone even number. The use of the filter method takes care of this checking to see if the number is divisible by 2. We stop at 4 million because of the takewhile method.

## Reply