Roskoto - 2 years ago 139

Python Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**