Skip to content

Instantly share code, notes, and snippets.

@djtango
Created December 1, 2018 20:07
Show Gist options
  • Save djtango/fa9dee21031dd6fcef1735d877986a41 to your computer and use it in GitHub Desktop.
Save djtango/fa9dee21031dd6fcef1735d877986a41 to your computer and use it in GitHub Desktop.
A horrible abuse of spec and laziness
(ns prime
(:require [clojure.spec.alpha :as s]))
(s/def ::prime-number
(fn [x]
(cond (<= x 1) false
(= 2 x) true
:else
(let [naturals (drop 2 (map inc (range)))
primes (lazy-seq [2])]
(letfn
[(divisible-by? [numer denom]
(= (mod numer denom)
0))
(find-next-prime [naturals primes]
(let [factor-predicates (map (fn [p] #(divisible-by? % p)) primes)
factor-of-primes? (fn [i] (some (fn [pred] (pred i)) factor-predicates))]
(drop-while factor-of-primes? naturals)))
(sieve [naturals primes]
(let [[next-prime & rest-of-naturals] (find-next-prime naturals primes)]
(lazy-seq
(cons next-prime (sieve rest-of-naturals
(cons next-prime primes))))))]
(contains?
(->> (sieve naturals primes)
(take-while #(>= x %))
(into #{}))
x))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment