Last active
December 16, 2015 14:09
-
-
Save pbalduino/5446627 to your computer and use it in GitHub Desktop.
Trying to solve the Euler #04 The recursive way
This file contains hidden or 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
(ns euler.euler04-1) | |
(defn peel | |
"Peel a string like a banana, removing first and last character" | |
[str] | |
(butlast (rest str))) | |
(defn palindrome? | |
"Returns true or false if name is a palindrome. | |
This recursive approach is slightly faster than compare with its reverse." | |
[name] | |
(let [f (first name) | |
l (last name)] | |
(if (or (empty? name) (not= f l)) | |
(= f l) | |
(recur (peel name))))) | |
(defn largest-palindrome | |
" 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." | |
[] | |
(loop [a 999 | |
big 0] | |
(let [r (loop [b a | |
p2 (palindrome? (str (* a b)))] | |
(if | |
(and | |
(> b 99) | |
(not p2)) | |
(recur (dec b) | |
(palindrome? (str (* a (dec b))))) | |
(* a b)))] | |
(if | |
(and | |
(> a 99)) | |
(recur (dec a) | |
(if (> r big) | |
r | |
big)) | |
big)))) | |
(defn -main [] | |
(time (println (largest-palindrome)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment