Sunday, November 30, 2014

Project Euler Problem 14 Common Lisp

Project Euler Problem 14

This solution is brute force but still took less that 4 seconds on my computer to return the answer.  Note, because the function position is zero based, I had to cons a zero onto the functions list parameter in order to get the correct answer.

(defun chain-length (n)
  (loop for i = n then (if (oddp i)
                         (1+ (* 3 i))
                         (/ i 2))
        counting i
        while (/= i 1)))

(defun problem14 ()
  (loop for i from 1 to 999999
        collect (chain-length i) into lst
        finally (return (position
                          (reduce #'max lst)
                          (cons 0 lst)))))

No comments:

Post a Comment