[Tutor] Writing a prime number program using upper bound of square root of n

Denis Gomes denisg640 at gmail.com
Sun Aug 22 23:48:03 CEST 2010


Nick,

   If you are using python 2.X, xrange(2,n) is just like range(2,n), the
xrange function is faster.  In python 3.X, they got rid of the slower range
function and renamed xrange to range.  The x in [x for x in xrange...] will
just go from 2 to the number n, but not including n.  This brings up a
possible issue.  You may or may not want to include that number n if n
itself is a prime number, therefore you should add 1 to n.  The code should
then go as follows.

def p(n):
     return [2,3,5,7]+[x for x in xrange(2,n+1) if x%2!=0 and x%3!=0 and
x%5!=0 and x%7!=0]

Denis


On Sun, Aug 22, 2010 at 5:10 PM, Nick <nblack3 at student.gsu.edu> wrote:

>  I will play with this and see what happens.  One question though,  [x for
> x in xrange(2,n) ..  what is xrange or is this an error?
>  ------------------------------
> *From:* Denis Gomes [denisg640 at gmail.com]
> *Sent:* Sunday, August 22, 2010 4:07 PM
> *To:* Nick
> *Subject:* Re: [Tutor] Writing a prime number program using upper bound of
> square root of n
>
>  Hey Nick,
>
>    You can also try using list comprehensions to do the same thing.  You
> could do something as follows:
>
> def p(n):
>      return [2,3,5,7]+[x for x in xrange(2,n) if x%2!=0 and x%3!=0 and
> x%5!=0 and x%7!=0]
>
>    This is cleaner and probably faster. More Pythonic.
>
> Denis
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100822/c1d6b855/attachment.html>


More information about the Tutor mailing list