Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure prime numbers lazy sequence

Tags:

python

clojure

What is the Clojure equivalent (for the exact algorithm) of the following Python code?

from itertools import count
from math import sqrt

def prime_gen():
   primes = []
   for n in count(2):
       if all(n%p for p in primes if p <= sqrt(n)):
           primes.append(n)
           yield n
like image 455
Roskoto Avatar asked Oct 19 '09 19:10

Roskoto


1 Answers

This is as Pythonish as I can make it:

(def prime-gen
     (let [primes (atom [])]
       (for [n (iterate inc 2)
             :when (not-any? #(zero? (rem n %))
                             (filter #(<= % (Math/sqrt n)) 
                                     @primes))]
         (do (swap! primes conj n)
             n))))

(take 10 prime-gen)  ; => (2 3 5 7 11 13 17 19 23 29)

Clojure doesn't consider the integer 0 to be boolean false. It took me a few minutes to figure out that your Python code was taking advantage of this.

Here are some other prime number algorithms in Clojure. There's also a prime number implementation in clojure.contrib.lazy-seqs.

like image 94
Brian Carper Avatar answered Sep 30 '22 07:09

Brian Carper