Skip to content

Instantly share code, notes, and snippets.

@tnoda
Forked from Kuchitama/Probrem1.clj
Created November 14, 2012 12:25
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 tnoda/4071827 to your computer and use it in GitHub Desktop.
Save tnoda/4071827 to your computer and use it in GitHub Desktop.
Nine solutions to Problem 1 of Project Euler in Clojure

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


Retrieved from http://projecteuler.net/problem=1, on Nov 14 2012.

;;; The original solution written by @kuchitama.
(apply +
(filter #(or (= (mod % 3) 0) (= (mod % 5) 0))
(range 1 1000)))
(loop [n 1 sum 0]
(if (< n 1000)
(if (or (zero? (rem n 3)) (zero? (rem n 5)))
(recur (inc n) (+ sum n))
(recur (inc n) sum))
sum))
(loop [n 1
sum 0]
(if (< n 1000)
(recur (inc n)
(if (or (zero? (rem n 3))
(zero? (rem n 5)))
(+ n sum)
sum))
sum))
(->> (range 1 1000)
(map #(if (or (zero? (rem % 3)) (zero? (rem % 5))) % 0))
(apply +))
(letfn [(next-val
[x]
(let [y (inc x)]
(if (or (zero? (rem y 3)) (zero? (rem y 5)))
y
(recur y))))]
(->> (iterate next-val 0)
(take-while #(< % 1000))
(apply +)))
(->> (concat (range 0 1000 3) (range 0 1000 5))
distinct
(apply +))
(apply + (concat (range 0 1000 3) (range 0 1000 5) (range 0 -1000 -15)))
(let [f #(let [n (quot 1000 %)] (* 1/2 n (inc n) %))]
(-> (+ (f 3) (f 5))
(- (f 15))))
(definline f
[x]
`(let [n# (quot 1000 ~x)]
(-> (* n# (inc n#) ~x) (quot 2))))
(-> (+ (f 3) (f 5)) (- (f 15)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment