-
-
Notifications
You must be signed in to change notification settings - Fork 159
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c8308c5
commit cae90f0
Showing
1 changed file
with
14 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)))) |