#!/usr/bin/env pugs

=begin Problem
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 one million.
=cut

use v6;
use Benchmark;

sub fib($n) {
    my @fibs = (0, 1);

    for ^($n - 1) {
        @fibs = (@fibs[1], @fibs[0] + @fibs[1])
    }

    @fibs[1];
}


sub main {
    my $sum = 0;
    my $fib;

    for 2..* -> $i {
        $fib = fib($i);

        last if $fib >= 1_000_000;

        $sum += $fib if $fib % 2 == 0;
    }
    say $sum;
}

my @t = timeit(1, \&main);
say "execution time: @t[0]";
