Fast Prime Number Generation in Clojure

后端 未结 16 1843
萌比男神i
萌比男神i 2020-12-02 12:30

I\'ve been working on solving Project Euler problems in Clojure to get better, and I\'ve already run into prime number generation a couple of times. My problem is that it is

16条回答
  •  时光取名叫无心
    2020-12-02 12:48

    See the last example here: http://clojuredocs.org/clojure_core/clojure.core/lazy-seq

    ;; An example combining lazy sequences with higher order functions
    ;; Generate prime numbers using Eratosthenes Sieve
    ;; See http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    ;; Note that the starting set of sieved numbers should be
    ;; the set of integers starting with 2 i.e., (iterate inc 2) 
    (defn sieve [s]
      (cons (first s)
            (lazy-seq (sieve (filter #(not= 0 (mod % (first s)))
                                     (rest s))))))
    
    user=> (take 20 (sieve (iterate inc 2)))
    (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)
    

提交回复
热议问题