Skip to content

Instantly share code, notes, and snippets.

@squarepegsys
Created October 18, 2021 15:12
Show Gist options
  • Save squarepegsys/3544d682933bed22d2da5c449e00ebfc to your computer and use it in GitHub Desktop.
Save squarepegsys/3544d682933bed22d2da5c449e00ebfc to your computer and use it in GitHub Desktop.
My Clojure Sieve of Eratosthenes
(defn sieve
([numbers primes composites]
(cond (empty? numbers) primes
(contains? composites (first numbers) ) (do (sieve (rest numbers) primes composites))
:else (do
(def current (first numbers))
(def new-primes (conj primes current))
(def new-composites
(into (sorted-set) (concat composites (range (* 2 current ) (inc (last numbers)) current))))
(sieve (seq(rest numbers)) new-primes new-composites))))
([number] (sieve (range 2 (inc number)) [] (sorted-set))))
@squarepegsys
Copy link
Author

use (sieve <int>) to find all the prime numbers from 2 to, inclusive
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment