Skip to content

Commit

Permalink
simplify example solution
Browse files Browse the repository at this point in the history
  • Loading branch information
tasxatzial committed Feb 19, 2025
1 parent c8308c5 commit cae90f0
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions exercises/practice/sieve/.meta/example.clj
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
(ns sieve)
(ns sieve
(:require [clojure.math :as math]))

(defn non-even-composites
[n]
(for [i (range 3 (inc (int (math/sqrt n))) 2)
k (range i (inc (int (/ n i))) 2)]
(* i k)))

(defn sieve
"Returns a list of primes less than or equal to limit"
[limit]
(loop [current-sieve (concat [false false] (range 2 (inc limit)))
last-prime 1]
(let [current-prime (->> current-sieve
(drop (inc last-prime))
(some identity))]
(if current-prime
(recur (map #(and %1 %2)
(concat (repeat (inc current-prime) true)
(cycle (concat (repeat (dec current-prime) true)
[false])))
current-sieve)
current-prime)
(filter identity current-sieve)))))
[n]
(if (< n 2)
()
(let [candidates (cons 2 (range 3 (inc n) 2))
composites (set (non-even-composites n))]
(remove composites candidates))))

0 comments on commit cae90f0

Please sign in to comment.