<p>你想要的是:</p>
<pre><code>def primes (q) :
# return (i for i in xrange(2,q) if i not in [j*k for j in xrange(1,i) for k in xrange(1,i)])
# return (i for i in xrange(2,q) if i not in [j*k for j in xrange(1,i) for k in xrange(1,j+1)])
# return (i for i in xrange(2,q) if i not in [j*k for j in xrange(1,i/2+1) for k in xrange(1,j+1)])
return (i for i in xrange(2,q) if i not in [j*k for j in xrange(1,i/2+1) for k in xrange(1,min(j+1,i/j+1))])
</code></pre>
<p>在Haskell中,范围是包含的,因此<code>primes(542)</code></p>
<pre><code>[n | n<-[2..541], not $ elem n [j*k | j<-[1..n-1], k<-[1..n-1]]] -- 25.66s
[n | n<-[2..541], not $ elem n [j*k | j<-[1..n-1], k<-[1..j]]] -- 15.30s
[n | n<-[2..541], not $ elem n [j*k | j<-[1..n`div`2], k<-[1..j]]] -- 6.00s
-- 0.79s
[n | n<-[2..541], not $ elem n [j*k | j<-[1..n`div`2], k<-[1..min j (n`div`j)]]]
</code></pre>
<p>实际上,<em><code>1*x == x</code></em>所以<em>1</em>不需要作为乘数,因此应该是</p>
<pre><code>[n | n<-[2..541], not $ elem n [j*k | j<-[2..n`div`2], k<-[2..min j (n`div`j)]]]
</code></pre>
<p>只需要0.59秒。或者,在Python中</p>
<pre><code>def primes (q) :
return (i for i in xrange(2,q) if i not in [j*k for j in xrange(2,i/2+1) for k in xrange(2,min(j+1,i/j+1))])
</code></pre>
<hr/>
<p><em>更新:</em>出于某种原因,<code>min j ...</code>没有多大区别,至少在Haskell中是这样。所以表达变得简单</p>
<pre><code>[n | n<-[2..541], not $ elem n [j*k | j<-[2..n`div`2], k<-[2..n`div`j]]]
</code></pre>