# Project Euler Problem 45 With the tricks we learned in the last problem, solving problem 45 was a snap.

(def triangle-nums (map #(bit-shift-right (* % (dec %)) 1) (iterate inc 2)))

(defn pentagonal? [n]
(zero? (rem (+ 1 (Math/sqrt (+ 1 (* 24 n)))) 6)))

(defn hexagonal? [n]
(zero? (rem (+ 1 (Math/sqrt (+ 1 (* 8 n)))) 4)))

(defn euler-45 []
(first (drop 2 (filter #(and (pentagonal? %)
(hexagonal? %))
triangle-nums))))

(time (euler-45)) ;; "Elapsed time: 147.319195 msecs"


One of the more straightforward solutions, I think. The obvious optimization from reading wikipedia is to realize that all hexagonal numbers are also triangular, so we can generate the hexagonal numbers directly and they will necessarily be triangular.

(def hexagonal-nums (map #(* % (dec (* 2 %))) (iterate inc 1)))

(defn pentagonal? [n]
(zero? (rem (+ 1 (Math/sqrt (+ 1 (* 24 n)))) 6)))

(defn euler-45-revised []
(first (drop 2 (filter pentagonal? hexagonal-nums))))

(time (euler-45-revised)) ;; "Elapsed time: 11.504974 msecs"


See you tomorrow!