## Posts Tagged ‘Euler’

### Euler #2

June 24, 2010

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.”

```> say ~(1, 1, *+* ... 4000000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578
```

Then `grep` filters on the test `* !% 2`. `!%` is the “divisible by” operator; `* !% 2` generates a closure that checks its one input for divisibility by 2.

```> say ~(1, 1, *+* ... 4000000).grep(* !% 2)
2 8 34 144 610 2584 10946 46368 196418 832040 3524578
```

Finally `[+]` is the reduce metaop for addition; it sums the list that follows.

I know that when people see one-liners, frequently they think the result has been golfed down. But this is really the natural way to express this problem in Perl 6.

Update: Very shortly after I wrote this, the “is divisible by” operator was changed to `%%`. At the moment, both versions of the operator work in Rakudo, but I would expect `!%` to go away eventually.