Sunday, April 10, 2016

Project Euler Problem 50 Common Lisp

Project Euler Problem 50

(defun prime? (num)
  (cond ((= 2 num) num)
    ((= 3 num) num)
    ((< num 1) nil)
    ((evenp num) nil)
    ((zerop (mod num 3)) nil)
    (t (loop for i from 5 to (isqrt num) by 6
        if (or (zerop (mod num i))
               (zerop (mod num (+ i 2)))) return nil
        finally (return num)))))

(defun primes (num)
  (append '(2 3)
      (loop for i from 5 to  num by 6
           if (prime? i) collect it
           if (prime? (+ i 2)) collect it)))

(defun prime-sums (num)
  (loop for i in (primes num)
     sum i into j
     unless (< num j)
     collect j))

(defun sum-of-consecutive-primes (num)
  (loop with sums = (prime-sums num)
       for i in sums
       collect (member-if #'prime?
              (loop for j in (cons 0 sums)
                   while (> i j)
                   collect (- i j)))))

(defun longest-sum-of-consecutive-primes (num)
  (let ((x (sort (sum-of-consecutive-primes num)

                 #'>
                 :key #'length)))
    (list (caar x) (length (first x)))))

(defun problem50 ()
  (let ((x (longest-sum-of-consecutive-primes 1000000)))
    (format t "The answer to Problem 50 is ~A with ~A terms."

            (first x) (second x))))

No comments:

Post a Comment