Fast Prime Number Generation in Clojure

后端 未结 16 1876
萌比男神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:38

    I realize this is a very old question, but I recently ended up looking for the same and the links here weren't what I'm looking for (restricted to functional types as much as possible, lazily generating ~every~ prime I want).

    I stumbled upon a nice F# implementation, so all credits are his. I merely ported it to Clojure:

    (defn gen-primes "Generates an infinite, lazy sequence of prime numbers"
      []
      (letfn [(reinsert [table x prime]
                 (update-in table [(+ prime x)] conj prime))
              (primes-step [table d]
                 (if-let [factors (get table d)]
                   (recur (reduce #(reinsert %1 d %2) (dissoc table d) factors)
                          (inc d))
                   (lazy-seq (cons d (primes-step (assoc table (* d d) (list d))
                                                  (inc d))))))]
        (primes-step {} 2)))
    

    Usage is simply

    (take 5 (gen-primes))    
    

提交回复
热议问题