PageRenderTime 18ms CodeModel.GetById 14ms app.highlight 3ms RepoModel.GetById 0ms app.codeStats 0ms

/014/14.scm

http://github.com/cfx/schemeuler
Scheme | 41 lines | 38 code | 2 blank | 1 comment | 0 complexity | 1b19d299a1b356ec51a971a9d81a6f01 MD5 | raw file
 1;;; a: 837799
 2
 3(define problem-14
 4  (lambda (n)
 5    (letrec ([t 0]
 6             [h (make-eqv-hashtable)]
 7             [S (lambda (n fn)
 8                  (cond
 9                   ((eq? n 1) (fn n 1))
10                   ((hashtable-ref h n #f)
11                    (fn n (hashtable-ref h n 0)))
12                   ((odd? n)
13                    (odd-seq n fn))
14                   (else (even-seq n fn))))]
15             [even-seq
16              (lambda (n fn)
17                (S (/ n 2) (col n fn)))]
18             [odd-seq
19              (lambda (n fn)
20                (S (+ 1 (* 3 n)) (col n fn)))]
21             [col (lambda (n fn)
22                    (lambda (ref val)
23                      (let ()
24                        (hashtable-set! h ref val)
25                        (set-t ref val)
26                        (fn n (+ val 1)))))]
27             [set-t (lambda (ref val)
28                      (if (< (hashtable-ref h t 0) val)
29                          (set! t ref)))])
30      (let loop ([n n])
31        (if (eq? n 1)
32            t
33            (let ()
34              (S n (lambda (ref val)
35                     (let ()
36                       (hashtable-set! h ref val)
37                       (set-t ref val)
38                       (hashtable-ref h ref 0))))
39              (loop (- n 1))))))))
40
41(display (problem-14 100000))