The following program requires a text file named primes_list.txt to be in the same directory as the .ipynb file which in this case is named PrimeInvestigation.ipynb. The file primes_list.txt must be a list of consecutive prime numbers with no space or punctuation separated by a carriage return after each number. It is fine to start with 2 as the first line and nothing else.
In [21]:
#Creates a list of integers from numbers in file primes_list.txt
with open("./primes_list.txt", "r") as f:
lines = f.readlines()
prime = [int(e.strip()) for e in lines]
def test_prime(candidate):
"""
Takes an argument which must be a positive integer and returns True
if it is prime False if it isn't. Will only work on numbers not more than
twice the size of the largest prime in primes_list.txt
"""
for i in prime:
#The number is not prime if it is evenly divided.
if candidate % i == 0:
return False
break
#If the number is not divisible by any prime number less than half it's size it is prime.
#Add it to the list of prime numbers.
elif i > candidate / 2:
write_prime(candidate)
return True
def write_prime(candidate):
"""
Appends the value of the variable candidate to the list called prime.
"""
prime.append(candidate)
def find_prime(hmny_more):
"""
Takes an argument which should be an int. It takes the last element of the list prime and adds 1 to
it and passes it to the function test_prime(candidate). It then adds one and repeats as many times as
the integer argument.
"""
print 'Welcome to Prime Finder! The largest prime catalogued so far is ', prime[-1]
candidate = prime[-1]
for i in range(hmny_more):
candidate += 1
test_prime(candidate)
return "Done. The largest prime catalogued on this run was", prime[-1]
def frequencyPrime(frequency):
count = 0
hundreds = frequency
for i in prime:
compare = int(i)
if compare < hundreds:
count += 1
#print i
else:
print hundreds - frequency, "-", hundreds, ":", count
hundreds += frequency
count = 0
#number = int(raw_input('How many more numbers would you like to check for primacy?: '))
#number = 100000
#find_prime(number)
#print prime
with open("./primes_list.txt", 'w') as f:
f.write("\n".join(map(str,prime)))
In [19]:
find_prime(1000)
Out[19]:
In [17]:
prime
Out[17]:
In [9]:
count = 0
hundreds = 1000
for i in prime:
compare = int(i)
if compare < hundreds:
count += 1
#print i
else:
print hundreds - 1000, "-", hundreds, ":", count
hundreds += 1000
count = 0
In [ ]:
In [10]:
count = 0
hundreds = 10000
for i in prime:
compare = int(i)
if compare < hundreds:
count += 1
#print i
else:
print hundreds - 10000, "-", hundreds, ":", count
hundreds += 10000
count = 0
In [ ]:
In [12]:
In [14]:
frequencyPrime(2000)
In [ ]: