Euler #2

Just saw a nice post with solutions to Euler problem #2 in several different languages.

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

This one is so easy in Perl 6 it’s not worth writing a script, I just did it as a one-liner in the REPL:

> say [+] (1, 1, *+* ... 4000000).grep(* !% 2)
4613732

Breaking it down: 1, 1, *+* ... * is the standard way to generate the infinite Fibonacci sequence in p6. It creates a list of numbers using the ... “series” operator. The list starts with 1, 1, and each additional number is created by adding the two previous numbers (that’s the *+* bit). The final * means the series has no limit. By switching the limit to 4000000 instead, we explicitly say “stop the series as soon as the number 4000000 is exceeded.”

7 Responses to “Euler #2”

I’ve been waiting for perl6 for a while and I’ve been playing with rakudo a bit lately. The (1,1, *+* .. *) thing is new to me. Was that invented specifically for fibonacci or does it have some other more practical use that’s eluding me?

Minor nit: the puzzle as you quoted it asks for a solution using a variation sequence which begins with 1,2, not 1,1. Of course, since 1,2,*+*…$n and 1,1,*+*…$n only differ in their first term, and the puzzle only cares about even elements, you get the same answer in both cases.

Eddward: the series op is pretty straight forward. I find this particular example more easily understood as 1,1,{$^a + $^b} … * though I will admit that it’s a lot longer. Whatever-currying is just a bit too magical for me just yet, but I’m sure I’ll get used to it.

Also, I really liked your solution to the problem in perl6. One of the best things about doing this blog series is getting to see everyone else’s solutions to these problems as well as their preferred languages. Its truly amazing what one can learn looking and studying other people’s code.