[Python] Python prime generator in one-line

Discussão em 'Python' iniciado por Stack, Janeiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create prime number generator in one-line of Python just as a fun exercise.

    The following code works as expected, but it is too slow:

    primes = lambda q: (i for i in xrange(1,q) if i not in [j*k for j in xrange(1,i) for k in xrange(1,i)])
    for i in primes(10):
    print i,


    So I I tried to do it by only checking up to the square-root of j and k:

    primes = lambda q: (i for i in xrange(1,q) if i not in [j*k for j in xrange(1,int(round(math.sqrt(i)+1))) for k in xrange(1,int(round(math.sqrt(i)+1)))])
    for i in primes(10):
    print i,


    But it outputs: 2 3 5 6 7 8

    So there must be something wrong with my indices j and k, but I haven't got a clue.

    Continue reading...

Compartilhe esta Página