Skip to content

Commit cae90f0

Browse files
committed
simplify example solution
1 parent c8308c5 commit cae90f0

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed
Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
1-
(ns sieve)
1+
(ns sieve
2+
(:require [clojure.math :as math]))
3+
4+
(defn non-even-composites
5+
[n]
6+
(for [i (range 3 (inc (int (math/sqrt n))) 2)
7+
k (range i (inc (int (/ n i))) 2)]
8+
(* i k)))
29

310
(defn sieve
4-
"Returns a list of primes less than or equal to limit"
5-
[limit]
6-
(loop [current-sieve (concat [false false] (range 2 (inc limit)))
7-
last-prime 1]
8-
(let [current-prime (->> current-sieve
9-
(drop (inc last-prime))
10-
(some identity))]
11-
(if current-prime
12-
(recur (map #(and %1 %2)
13-
(concat (repeat (inc current-prime) true)
14-
(cycle (concat (repeat (dec current-prime) true)
15-
[false])))
16-
current-sieve)
17-
current-prime)
18-
(filter identity current-sieve)))))
11+
[n]
12+
(if (< n 2)
13+
()
14+
(let [candidates (cons 2 (range 3 (inc n) 2))
15+
composites (set (non-even-composites n))]
16+
(remove composites candidates))))

0 commit comments

Comments
 (0)