-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsieve.py
executable file
·71 lines (57 loc) · 1.47 KB
/
sieve.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import threading, sys
target = int(sys.argv[1])
toWrite = []
output = open('primes.txt', 'w')
class WriteOutPrimes(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
try:
value = toWrite.pop(0)
if value != None and value != 'Done':
output.write(str(value) + '\n')
elif value == 'Done':
print 'CCCThread done, dying...'
break
except IndexError:
continue
source = []
primes = []
outputThread = WriteOutPrimes()
outputThread.start()
print 'Generating source map...'
for i in range(1, target + 1):
source.append(1)
print 'Beginning calculations.'
for i in range(2, target):
try:
if source[i] == 1:
toWrite.append(i)
primes.append(i)
for j in range(i+i, target, i):
try:
source[j] = 0
except IndexError:
print 'IndexError in all-loop', str(i), str(j)
continue
except IndexError:
print 'IndexError at main loop', str(i)
except KeyboardInterrupt:
print 'Received interrupt, shutting down promptly.'
toWrite.append('Done')
quit()
if i == (target / 2):
print 'Halfway there in calculations...'
toWrite.append('Done')
print 'killing child thread, awaiting join'
outputThread.join(5) # Wait 5 seconds for thread to be done, then proceed anyway.
output.close()
print 'closing file object'
for i in range(1, len(primes), 5):
try:
# print "PRIME:", primes[i], primes[i+1], primes[i+2], primes[i+3], primes[i+4]
except:
continue
print 'program closing'
quit()