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)
b
(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)

Code for My Solution the the First Euler Problem

This was basically the first scheme program I have ever written and the first program i have written in about 4 years, so yes, I know the code is very sloppy...

(define (testdiv n f)
(cond ((= (remainder n f) 0) 1)
(else 0)))
(define (buildlist n m)
(cond ((> n 0) (buildlist (- n 1) (cons n m)))
((= n 0) m)))
(define (test2div n f1 f2)
(cond ((= (testdiv n f1) 1) n)
((= (testdiv n f2) 1) n)
(else 0)))
(define (euler1 n f1 f2)
(cond ((not (empty? (cdr n))) (+ (test2div (car n) f1 f2) (euler1 (cdr n) f1 f2)))
(else (test2div (car n) f1 f2))))


It worked but due to the fact that its been 2 weeks since I wrote it and the code is ugly as hell I cant for the life of me remember how I call it. sure, I could probably figure out how, but if I had any desire to go back to this problem I would almost certainly scrap this and rewrite the code entirely..

Saturday, January 24, 2009

A bit of a change of pace...

Well its been a while, a while since you, oh non-existent reader and i sat down here on this masturbatory exercise of a blog and had a catch up and the obligatory change of pace.

So, to start, lets get caught up. I am enjoying myself in Oakland, have a nice new apartment and a job that while is not great affords me time to think, Time to study, Time to relax. In that time i have started working on getting my math up to par, to this end I have begun some slight work on the Project Euler problems. to accomplish this I have begun to learn the programming language SCHEME. I have started this by working my way though MIT's "Structure and Interpretation of Computer Programs".To that end i will be posting here my solutions to both the exercises of that book and the Project Euler problems.