SICP and Project Euler
Working my way through SICP has a goal I’ve had for a while but never seemed to get to. However – this past week I started reading the book and working on the exercises and am looking forward to the challenge. I skipped a couple of exercises in the first section but came up with the following to exercise 1.8:
(define (cube x) (* x x x)) (define (abs-val x) (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x)))) (define (improve guess x) (/ (+ (/ x (* guess guess)) (* 2 guess)) 3)) (define (good-enough? guess x) (< (abs-val (- (cube guess) x)) 0.001)) (define (cube-root-iter guess x) (if (good-enough? guess x) guess (cube-root-iter (improve guess x) x))) (define (cube-root x) (cube-root-iter 1.0 x))
Along with the exercises in SICP I plan to also apply my new found knowledge to some of the problems from Project Euler. The solution I came up with for exercise 1 was probably overkill but it worked and should work for larger sets of numbers:
(define (calc-iter total count limit) (if (= count limit) total (calc-iter (+ (if (or (= (modulo count 3) 0) (= (modulo count 5) 0)) count 0) total) (+ count 1) limit))) (define (calc x) (calc-iter 0 0 x)) (calc 1000)