
Finally got some code working with saving the Primes on a DB. I started by saving as I find the prime and realised that the constant IO activity was slowing the all process down. Next step was multi treading: this is still not 100%. Here is the code so far:
# Python program to calculate prime numbers
import math
import threading
import sqlite3
count = 0
primeList = []
dbname='/home/roberto/primelist.db'
table_name = 'primes' # name of the table to be created
new_field = 'prime' # name of the column
field_type = 'INTEGER' # column data type
def save_primes(number, topnum):
while True:
add_prime(primeList[number])
number +=1
if number == (topnum - 1):
break
def createDB():
# Connecting to the database file
conn = sqlite3.connect(dbname)
c = conn.cursor()
try:
#c.execute('select prime from primes')
#primeList = c.fetchall()
for row in c.execute('select prime from primes'):
primeList.append(int(row[0]))
except:
# Creating a new SQLite table with 1 column
c.execute('CREATE TABLE {tn} ({nf} {ft})'\
.format(tn=table_name, nf=new_field, ft=field_type))
# Committing changes and closing the connection to the database file
conn.commit()
conn.close()
def add_prime(prime):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
curs.execute("INSERT INTO primes values((?))", (prime,))
# commit the changes
conn.commit()
conn.close()
def isPrime(num):
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(len(primeList)):
if (num % primeList[i]) == 0:
#print(num,"is not a prime number")
#print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
primeList.append(num)
#add_prime(num)
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
#start
createDB()
if len(primeList) == 0:
num = 1
count = 0
else:
num = primeList[len(primeList)-1]+1
count = len(primeList)
while True:
isPrime(num)
num += 1
#this logic will save the primes async to avoid slow IO
if (num % math.pow(10, 4))==0:
t = threading.Thread(target=save_primes, args=(count, len(primeList), ))
t.start()
count = len(primeList)
if num == math.pow(10, 101):
break