Welcome, guest | Sign In | My Account | Store | Cart

This program is to produce prime numbers less than and equal to n.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def primes(n):    
    if n <= 1:
        print('No primes.')        
        return False    
    n = int(n)       
    p = list(range(1,n+1,2)) # in Python 3, range can't be assigned;
    q = len(p)
    p[0] = 2
    for i in range(3,int(n**.5)+1,2):
        if p[(i-1)//2]:            
            p[(i*i-1)//2:q:i] = [0]*((q-(i*i+1)//2)//i+1)           
    return [x for x in p if x]

1 comment

wycao2k (author) 11 years, 10 months ago  # | flag

As I tested so far, this is the fastest python code.

Created by wycao2k on Tue, 5 Jun 2012 (MIT)
Python recipes (4591)
wycao2k's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks