diff options
-rw-r--r-- | problem-14.scm | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/problem-14.scm b/problem-14.scm new file mode 100644 index 0000000..9f58656 --- /dev/null +++ b/problem-14.scm @@ -0,0 +1,42 @@ +;;; +;;; Problem 14: Longest Collatz Sequence +;;; + +;;; https://projecteuler.net/problem=14 + +(use-modules (srfi srfi-1)) + +(define (collatz n) + (if (even? n) + (/ n 2) + (+ (* 3 n) 1))) + +(define (collatz-fold n init proc) + (let loop ((n n) + (result init)) + (if (= n 1) + result + (let ((c (collatz n))) + (loop c (proc c result)))))) + +(define (collatz-length n) + "Return the length of the Collatz sequence for N" + (collatz-fold n 1 (lambda (n length) (1+ length)))) + +;; Just for fun. +(define (collatz-sequence n) + "Return the Collatz sequence for N." + (reverse (collatz-fold n (list n) cons))) + +(define (longest-collatz up-to) + (let loop ((n 13) + (m 13) + (length 10)) + (if (>= n up-to) + m + (let ((l (collatz-length n))) + (if (> l length) + (loop (1+ n) n l) + (loop (1+ n) m length)))))) + +(longest-collatz (expt 10 6)) |