Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created March 25, 2012 15:19
Show Gist options
  • Select an option

  • Save martintrojer/2197227 to your computer and use it in GitHub Desktop.

Select an option

Save martintrojer/2197227 to your computer and use it in GitHub Desktop.
Prime number estimation
(defn prime? [x]
(let [divs (range 2 (inc (int (Math/sqrt x))))
rems (map #(rem x %) divs)]
(not (some zero? rems))))
(filter prime? (range 1000))
(defn expmod
"calculates (base**exp) % m"
[base exp m]
(letfn [(sq [x] (* x x))]
(cond
(= exp 0) 1
(even? exp) (rem (sq (expmod base (/ exp 2) m)) m)
:else (rem (* base (expmod base (- exp 1) m)) m))))
(defn fermat-test [n]
(letfn [(try [a](= (expmod a n n) a))]
(try (+ 1 (rand-int (- n 1))))))
(defn prime? [n times]
(cond
(= times 0) true
(fermat-test n) (prime? n (- times 1))
:else false))
(->> (iterate inc 1) (drop-while #(< % 1000)) (filter #(prime? % 5)) (take 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment