Saturday, January 31, 2009

Solution to Problem 2 of Project Euler

My solution to problem 2 was done shortly after solving problem 1, so you can see the progression of my Scheme programming, still not as sharp as it could be, (and I didn't even try to explore the interesting mathematical attacks on the problem, I'm still using the problems as exercises in coding and not yet looking at them as math problems, something I imagine I wont be able to keep up for long...

(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
(fib-iter (+ a b) a (- count 1))))
(define (fib< n)
(fib<-iter n 1 empty))
(define (fib<-iter n count l)
(cond ((> n (fib count)) (fib<-iter n (+ count 1) (cons (fib count) l)))
(else l)))
(define (euler2 n)
(euler2-iter (fib< n) 0))
(define (euler2-iter l sum)
(cond ((not (empty? l))
(cond ((even? (car l)) (euler2-iter (cdr l) (+ (car l) sum)))
(else (euler2-iter (cdr l) sum))))
(else sum)))

then I call the function by (euler2 4000000)

No comments: