Gosh. It's been
a long time since the first one of these. I have been slacking.
I meant to get round to doing
Project Euler, problem 2 last weekend, but, well, life. So I've been having a go this weekend, and tore chunks of my hair out over it for the past couple of days.
Still, I figured it out in the end. Only took 'til Monday lunchtime.
(
euler-2.scm )
Comments 6
top=4000000
penultimate=0
last=1
current=1
sum=0
while current<=top:
if current%2==0:
sum+=current
(penultimate, last)=(last, current)
current=penultimate+last
print sum
Not sure how I'd go about that in a functional programming idiom, though.
Reply
def add_even_fib(max, prev, cur):
if prev + cur > max:
return 0
if prev + cur % 2 == 0:
return prev + cur + add_even_fib(max, cur, prev + cur)
else:
return add_even_fib(max, cur, prev + cur)
print add_even_fib(4000000, 0, 1)
Reply
def fibgen(top):
last,cur=1,1
while cur<=top:
yield cur
last,cur=cur,last+cur
print sum(n for n in fibgen(4e6) if n%2==0)
Reply
However, I'm not nearly at the point where I can do continuations yet, so I stuck to creating the whole list at once.
Reply
$phi = ( 1 + pow( 5, 0.5 ) ) / 2;
$psi = 1 - $phi;
$sum = 0;
$f = 2;
for( $i = 3; $f < 4000000; $i += 3 )
{
$sum += $f;
// http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
$f = ( pow( $phi, $i ) - pow( $psi, $i ) ) / pow( 5, 0.5 );
}
print "{$sum}\n";
I can only assume I was being deliberately perverse!
Reply
Reply
Leave a comment