Skip to content

Instantly share code, notes, and snippets.

@mowen
Created February 3, 2010 14:59
Show Gist options
  • Save mowen/293659 to your computer and use it in GitHub Desktop.
Save mowen/293659 to your computer and use it in GitHub Desktop.
;; 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.
;;
(defun array-reverse (array)
"Reverse the ARRAY."
(let ((reversed-array (copy-sequence array))
(array-length (length array))
(i 0))
(while (< i array-length)
(aset reversed-array i (aref array (- array-length 1 i)))
(setq i (1+ i)))
reversed-array))
(defun palindrome-p (num)
"Is the number a palindrome?"
(let* ((num-string (number-to-string num))
(num-length (length num-string)))
(if (= 0 (% num-length 2)) ;; length is even
(progn
(let* ((num-centre (/ num-length 2))
(first-half (substring num-string 0 num-centre))
(second-half (substring num-string num-centre num-length)))
(string= first-half (array-reverse second-half))))
nil)))
(defun build-number-pair-permutations (limit)
"Build a list of the permutations of the numbers."
(let ((list '())
(num1 limit)
(num2 limit))
(while (> num2 0)
(while (> num1 0)
(setq list (cons (list num1 num2) list))
(setq num1 (1- num1)))
(setq num1 limit)
(setq num2 (1- num2)))
list))
(defun product-is-palindrome (pair)
"Is the product of the pair of numbers a palindrome?"
(let ((product (* (car pair) (cadr pair))))
(if (palindrome-p product)
product)))
(defun find-palindromes (permutations)
"Find the palindromes from the products of the given permutations."
(mapcar 'product-is-palindrome permutations))
(defun euler-4 (limit)
"Solution to Project Euler 4."
(let* ((permutations (build-number-pair-permutations limit))
(palindromes (find-palindromes permutations)))
(setq palindromes (remove nil palindromes))
(car (sort palindromes '>))))
(euler-4 999) ;; 906609
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment