Skip to content

Instantly share code, notes, and snippets.

@bdesham
Created July 10, 2011 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdesham/1074160 to your computer and use it in GitHub Desktop.
Save bdesham/1074160 to your computer and use it in GitHub Desktop.
Clojure implementation of Project Euler problem 12
;; Utility functions that will be used later
(def naturals (iterate inc 1))
(defn all-factors
[n]
(filter #(= (mod n %) 0)
(take-while #(<= % (sqrt n))
(rest naturals))))
(defn first-matching
"Given a function and a sequence, return the first element of the sequence for
which the function returns true."
[f s]
(if (f (first s))
(first s)
(if (seq (rest s))
(recur f (rest s))
nil)))
;; Project Euler problem 12
(def triangle-numbers (map #(reduce + (take % naturals)) naturals))
(def problem12
(delay (first-matching #(> (count (all-factors #)) 500) triangle-numbers)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment