Created
February 13, 2012 16:57
-
-
Save jld/1818271 to your computer and use it in GitHub Desktop.
Euler Project Problem 14 solution, written on a Monday morning while mostly asleep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; http://projecteuler.net/problem=14 | |
(define (eu14 m) | |
(let ((memo (make-vector m #f)) | |
(best-l 0) | |
(best-i 0)) | |
(define (up n a) | |
(cond | |
((= n 1) a) | |
((and (< n m) (vector-ref memo n)) => (lambda (x) (+ a x))) | |
((even? n) (up (/ n 2) (+ a 1))) | |
(else (up (+ (* n 3) 1) (+ a 1))))) | |
(define (down n a) | |
(if (not (and (< n m) (vector-ref memo n))) | |
(begin | |
(if (< n m) (vector-set! memo n a)) | |
(cond | |
((= n 1) #t) | |
((even? n) (down (/ n 2) (- a 1))) | |
(else (down (+ (* n 3) 1) (- a 1))))))) | |
(let loop ((n 1)) | |
(if (< n m) | |
(let ((nl (up n 0))) | |
(down n nl) | |
(if (< best-l nl) | |
(begin | |
(set! best-l nl) | |
(set! best-i n))) | |
(loop (+ n 2))))) | |
best-i)) | |
; > (time (eu14 1000000)) | |
; Words allocated: 839670 | |
; Words reclaimed: 0 | |
; Elapsed time...: 306 ms (User: 308 ms; System: 0 ms) | |
; Elapsed GC time: 0 ms (CPU: 0 in 1 collections.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment