标签:style io color sp for strong on div cti
Difficulty: | Medium |
Topics: | primes |
(defn prime?
[n]
(if (= 2 n)
true
(empty? (for [i (range 2 (inc (Math/sqrt n)))
:let [r (mod n i)]
:when (zero? r)] i))))
测试20以内的质数:(map #(hash-map % (prime? %)) (range 2 20))
;({2 true} {3 true} {4 false} {5 true} {6 false} {7 true} {8 false} {9 false} {10 false} {11 true} {12 false} {13 true} {14 false} {15 false} {16 false} {17 true} {18 false} {19 true})
把这个函数与seq合并:(take 5 (filter prime? (iterate inc 2)))
;(2 3 5 7 11)
最后,所有中间过程重写成匿名,重写组织:
(fn [x] (take x (filter
(fn [n (if (= 2 n) true (empty? (for [i (range 2 (+ 1(Math/sqrt n))) :let [r (mod n i)] :when (= 0 r)] i)))) (iterate inc 2))))
标签:style io color sp for strong on div cti
原文地址:http://www.cnblogs.com/zjfu/p/4124734.html