Created
February 3, 2010 14:59
-
-
Save mowen/293659 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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