A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
Find the largest palindrome made from the product of two 3-digit numbers.
My Solution
(defun palindrome(n)
(let ((numberstr (format nil "~a" n)))
(string= numberstr (reverse numberstr))))
(defun Euler4()
(loop for i from 100 to 999
do(loop for j from 100 to 999
do(if (and (palindrome (* i j))
(zerop (rem (* i j) i))
(zerop (rem (* i j) j)))
(print (* i j))))))
Others' Solution
First Solution
(defun digits (num)
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
(defun palindromep (lst)
(or (< (length lst) 2)
(and (equal (car lst) (car (last lst)))
(palindromep (cdr (butlast lst))))))
(defun prod-list (min max j)
(loop for i from min to max collecting (* i j)))
(defun all-prods (min max)
(loop for j from min to max appending (prod-list min j j)))
(defun euler4 ()
(apply #'max (remove-if-not
#'(lambda (n) (palindromep (digits n)))
(all-prods 100 999))))
(map 'list
#'(lambda (char) (read-from-string (string char)))
(prin1-to-string num)))
(defun palindromep (lst)
(or (< (length lst) 2)
(and (equal (car lst) (car (last lst)))
(palindromep (cdr (butlast lst))))))
(defun prod-list (min max j)
(loop for i from min to max collecting (* i j)))
(defun all-prods (min max)
(loop for j from min to max appending (prod-list min j j)))
(defun euler4 ()
(apply #'max (remove-if-not
#'(lambda (n) (palindromep (digits n)))
(all-prods 100 999))))
Second Solution
(defun digits (n)
"extract base 10 digits from a number into a sequence"
(loop for input = n then (truncate (/ input 10))
until (= input 0)
for digit = (mod input 10)
collecting digit into digits
finally (return (reverse digits))))
until (= input 0)
for digit = (mod input 10)
collecting digit into digits
finally (return (reverse digits))))
(defun palindrome? (seq)
"returns t if a sequence is a palindrome"
(equal seq (reverse seq)))
"returns t if a sequence is a palindrome"
(equal seq (reverse seq)))
(defun problem-4 ()
(loop for n1 from 100 to 999
maximizing (loop for n2 from 100 to 999
and p = (* n1 n2)
maximizing
maximizing
(if (palindrome? (digits p)) p 0))))
Third Solution
(defun euler4 (&optional (n 999))
(let ((largest 0))
(do ((i 1 (+ i 1))) ((> i n) largest)
(do ((j 1 (+ j 1))) ((> j n) 'done)
(if (and (> (* i j) largest)
(string= (format nil "~A" (* i j))
(reverse (format nil "~A" (* i j)))))
(reverse (format nil "~A" (* i j)))))
(setf largest (* i j)))))))
No comments:
Post a Comment