summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Thompson <dthompson2@worcester.edu>2015-10-01 04:14:50 -0400
committerDavid Thompson <dthompson2@worcester.edu>2015-10-01 04:15:13 -0400
commitdd4cc3051689001803df35205462e31cfdbf9193 (patch)
tree722b090a763fc6e8ee49e819a32b5bdb7f725bac
parent695daa2df6cf556d087f859d8cb3ca2f3efec2f9 (diff)
Add Problem 14 solution.
-rw-r--r--problem-14.scm42
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))