Oregon Curriculum Network

Discovering Math with Python

The end goal is to verify the included program is getting all the primes it should be.

To this end, primes_file.txt contains the first 10,000 prime numbers, up to over 104,000.

First, lets see how we read in the file and turn it into a simple Python list, of primes only. This published list came from The Prime Pages.

```
In [1]:
```from IPython.display import YouTubeVideo
YouTubeVideo('V08g_lkKj6Q')

```
Out[1]:
```

```
In [2]:
```with open("primes_file.txt", "r") as primes:
output = []
for line in primes.readlines()[3:]: # skip first 4 lines
if line.strip() == 'end.':
break
for column in line.split():
num = int(column.strip())
output.append(num)

*output* will be global since the above cell is run top level, not inside the scope of a function. Checking the last few entries below, to confirm everything worked:

```
In [3]:
```# verify we have the data we want
print(output[0:10]) # first 10
print(output[-10: -1]) # last 10

```
```

So far I'm feeling pretty good about this one.

Lets check on primes to 1000. Up to 100,000 is left as an exercise to the more committed.

```
In [4]:
```from math import sqrt as root2, floor
def eratosthenes(n):
the_max = floor(root2(n)) # upper limit of eliminator
sieve = list(range(0, n+1))
eliminator = 2
while True:
if eliminator > the_max:
break
print("Eliminating multiples of:", eliminator)
for k in range(2 * eliminator, n + 1, eliminator):
sieve[k] = 0
while sieve[eliminator + 1] == 0:
eliminator += 1
else:
eliminator = sieve[eliminator + 1]
# shrink me down (compact the sieve)
sieve = [n for n in sieve if n != 0][1:] # list comprehension!
return sieve
# apply fancy formatting to output
output = eratosthenes(1000)
for row in range(0, len(output), 10):
print(", ".join(map(lambda s: str.format("{:3d}", s), output[row:row+10])))

```
```

Now we're interested in checking our list against the elements obtained from primes_file.txt, up to and including our largest prime.

We may simply count the primes we have, chop off that many from *output* and perform and equality test...

```
In [5]:
```how_many = len(output)
check_list = output[:how_many] # get as many from the published pool as are in the sieve
print(output == check_list) # check for equality

```
```