Skip to content

Instantly share code, notes, and snippets.

@jld
Created February 13, 2012 16:57
Show Gist options
  • Save jld/1818271 to your computer and use it in GitHub Desktop.
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
; 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