DEV Community

Discussion on: Project Euler #2 - Even Fibonacci numbers

Collapse
 
jacoby profile image
Dave Jacoby • Edited

I solved Euler 1-3 in 2015 but stopped...

#!/usr/bin/env perl
use feature qw{say state} ;
use bigint;
my $max = 4_000_000 ;

my $sum = 0 ;
while (1){
    state $i = 0;
    $i++;
    my $f = fibonacci($i);
    my $e = $f %2==0?1:0;
    last if $f > $max ;
    $sum += $f if $e;
    }
say $sum;

sub fibonacci {
    my $i = shift ;
    state $cache ;
    $cache->[0]=1;
    $cache->[1]=1;
    if ( $cache->[$i] ) { return $cache->[$i] }
    $cache->[$i] = $cache->[$i-1] + $cache->[$i-2] ;
    return $cache->[$i] ;
    }