The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
My Solution
(defun primep (n)
(cond ((= 2 n) t)
((evenp n) 'nil)
((= 1 n) 'nil)
(t (let ((limit (floor (sqrt n))))
(do ((i 3 (incf i 2)))
((> i limit) t)
(if (= 0 (mod n i)) (return-from primep 'nil)))))))
(defun enumerate-interval (low high)
(loop for i from low to high
collect i))
(defun primes(n)
(remove-if #'(lambda(x) (null x)) (loop for i from 3 to n by 2
collect (if (and (primep i) (not (null i))) i))))
(defun leftCycle(num)
(let ((numberstr (format nil "~a" num))
(IsLeftCycle T))
(loop for i from 0 to (- (length numberstr) 1)
do(if (not (primep (parse-integer numberstr :start i :end (length numberstr))))
(progn (setq IsLeftCycle nil)
(return IsLeftCycle))))
IsLeftCycle))
(defun rightCycle(num)
(let ((numberstr (format nil "~a" num))
(IsRightCycle T))
(loop for i from 1 to (length numberstr)
do (if (not (primep (parse-integer numberstr :start 0 :end (+ i))))
(progn (setq IsRightCycle nil)
(return IsRightCycle))))
IsRightCycle))
(defun Euler37(n)
(loop for i from 21 to n
when (and (rightCycle i)
(leftCycle i))
sum i))
No comments:
Post a Comment