Created
March 25, 2012 15:19
-
-
Save martintrojer/2197227 to your computer and use it in GitHub Desktop.
Prime number estimation
This file contains hidden or 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
| (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)) |
This file contains hidden or 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
| (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