#!/usr/bin/python
size = input("Enter the range to check: ")
# Make the range 1 ... 1000
r = range(0,size+1)
# for each non-crossed out entry
target = 2
while (target < size+1):
# if this entry is not
crossed out
if (r[target] != -1):
# it's prime! Print it
#print target
# then cross out every entry from target*2 step target
cross = target *2
while(cross < size+1):
r[cross] = -1
cross = cross + target
target = target + 1
import sys
import string
size = string.atoi(sys.argv[1])
result = []
candidates = range(3,size)
prime = 2
product = prime
while candidates:
result.append(prime)
while product < size:
if product in candidates:
candidates.remove(product)
product = product+prime
prime = candidates[0]
product = prime
del candidates[0]
#print result
#print "There were", len(result), "prime numbers below ", size
Size | Seive1 | Seive2 |
100 | 0.03 | 0.04 |
1000 | 0.04 | 0.17 |
2000 | 0.05 | 0.59 |
4000 | 0.08 | 2.31 |
8000 | 0.14 | 9.22 |
16000 | 0.26 | 36.72 |
It is best to think of a dictionary as an unordered set of key:value
pairs, with the requirement that the keys are unique (within one dictionary).
A pair of braces creates an empty dictionary: {}. Placing a
comma-separated list of key:value pairs within the braces adds initial
key:value pairs to the dictionary; this is also the way dictionaries are
written on output.
The main operations on a dictionary are storing a value with some key
and extracting the value given the key. It is also possible to delete a
key:value pair with del. If you store using a key that is already in use,
the old
value associated with that key is forgotten. It is an error to extract
a value using a non-existent key.
The keys() method of a dictionary object returns a list of all the keys
used in the dictionary, in random order (if you want it sorted, just apply
the sort() method to the list of keys). To check whether a single key is
in the
dictionary, use the has_key() method of the dictionary.
Here is a small example using a dictionary:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack':
4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack':
4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
1