Problem 4: Numeric Palindromes

14 10 2009

Find the largest palindrome which is the product of 2, 3 digit numbers

The challenge is to find a numeric palindrome which is the product of 2 numbers, both from 100 to 999.

(defn reverse-int [n]
    (loop [m n acc 0]
	(cond
       	    (zero? ) acc
	    :else (recur (quot m 10) (+ (* acc 10) (mod m 1))))))

(defn palindrome? [n]
    (= n (reverse-int n)))

(defn euler-4 [lower-limit upper-limit]
    (loop [p upper-limit q upper-limit largest 0]
	(let [candidate (* p q)]
    	    (cond
		(< p lower-limit) largest
		(< candidate largest) largest
		(< lower-limit q) (recur (dec p) (dec p) largest)
                (palindrome? candidate)
  	  	    (if (> candidate largest)
			(recur p (dec q) candidate))
		:else (recur p (dec q) largest)))))

(euler-4 100 999)

let like loop, forms a dynamic binding between the odd and even terms in the argument list for the expression in the body of the let.

(let [a 3 b 4]
    (+ a b))
=> 4

if takes 2 – 3 expressions as arguments, if the first one evaluates to be True, then the second (then) is evaluated, else the third (else) is evaluated. In this case there is no else clause, the control breaks out of the if statement

(if (< 2 3)
    4
    5)
=> 4

reverse-int takes an integer as argument and reverses it

(reverse-int 234)
=>432

palindrome? is a predicate which checks if an integer is a palindrome

(palindrome? 121)
=> True

There are 2 optimizations in this solution

1> Any 2 numbers are multiplied only once
2> If the largest palindrome found so far is larger than the current (* p q), return it


Actions

Information

Leave a comment