Skip to content

Instantly share code, notes, and snippets.

@psfblair
Created August 22, 2010 22:12
Show Gist options
  • Select an option

  • Save psfblair/544341 to your computer and use it in GitHub Desktop.

Select an option

Save psfblair/544341 to your computer and use it in GitHub Desktop.
; 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.
; The simple version -- didn't know that ranges had a start/end/step version
(apply +
(for [multiple (range 1000)
:when (or (= 0 (mod multiple 3))
(= 0 (mod multiple 5)))]
multiple)
)
; Refactoring
(defn multiple-of [x factor] (= 0 (mod x factor)))
(apply +
(for [multiple (range 1000)
:when (or (multiple-of multiple 3)
(multiple-of multiple 5))]
multiple)
)
; Refactoring, trying to simplify -- hah!
(defn multiple-of-one-of [x list-of-factors]
(not-every? false?
(for [factor list-of-factors]
(= (mod x factor) 0)))
)
(apply + (for [multiple (range 1000)
:when (multiple-of-one-of multiple '(3 5))]
multiple)
)
; Try again now that I know about step
(def multiplesOf3ButNot5 (for [multiple (range 0 1000 3)
:when (not= 0 (mod multiple 5))]
multiple))
(apply + (concat multiplesOf3ButNot5 (range 0 1000 5)))
; Or, to match the "efficient way" I did it in F#
(def multiplesOf3ButNot5 (for [multiple (range 0 1000 3)
:when (not= 0 (mod multiple 5))]
multiple))
(+ (apply + multiplesOf3ButNot5) (apply + (range 0 1000 5)))
; Alex's solution
(ns user (use clojure.set))
(def multiples (union (set (range 0 1000 3)) (set (range 0 1000 5))))
(reduce + multiples)
; Using a lazy list
(defn multiple-of [x factor] (= 0 (mod x factor)))
(def infinite (for [multiple (iterate inc 0)
:when (or (multiple-of multiple 3)
(multiple-of multiple 5))]
multiple))
(reduce + (take-while #(< % 1000) infinite))
; Another one from Alex
(def multiples (distinct (concat (range 0 1000 3) (range 0 1000 5))))
(apply + multiples)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment