Archive for the ‘project euler’ tag
Project Euler Problem 3 in Scheme
Since I’m working my way through SICP I ended up using some of the code from the examples in section 1.2.6 to search for prime numbers. Six of the eight functions below are used to test if a number is prime. (next-prime …) just starts at the current prime number and iterate upward until it finds the next prime number. (search-for-factors …) does the actual searching for prime factors.
(define (smallest-divisor n) (find-divisor n 2)) (define (divides? a b) (= (remainder b a) 0)) (define (square n) (* n n)) (define (next-divisor n) (if (= n 2) 3 (+ n 2))) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (next-divisor test-divisor))))) (define (prime? n) (= n (smallest-divisor n))) (define (next-prime n) (let ((m (+ n 1))) (if (prime? m) m (next-prime m)))) (define (search-for-factors n factor) (cond ((= (/ n factor) 1) (display factor) (newline)) ((divides? factor n) (display factor) (newline) (search-for-factors (/ n factor) factor)) (else (search-for-factors n (next-prime factor))))) (search-for-factors 600851475143 2)
Project Euler Problem 2 in Scheme
This one was relatively straight forward.
(define (fib-iter last-one last-two total max) (if (or (> (+ last-one last-two) max) (= (+ last-one last-two) max)) total (fib-iter (+ last-one last-two) last-one (if (= (modulo (+ last-one last-two) 2) 0) (+ total last-one last-two) total) max))) (fib-iter 1 0 0 4000000)
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)