From dd4cc3051689001803df35205462e31cfdbf9193 Mon Sep 17 00:00:00 2001 From: David Thompson Date: Thu, 1 Oct 2015 04:14:50 -0400 Subject: Add Problem 14 solution. --- problem-14.scm | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 problem-14.scm 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)) -- cgit v1.2.3