Please prepare prime.txt without contents separately.
prime.py
import math
num = 3 #Number to start exploration
prime = [2] #Add 2 to prime numbers
prm_cnt = 1 #A variable that counts the found prime numbers
pfile = 'prime.txt' #File to write the found prime number
####################################################################
#Function Description:Last executed prime number list file read function
####################################################################
def load_prime():
global prm_cnt
global prime
global num
file_data = open(pfile, "r")#File reading
print("!! load start !!\n")
for line in file_data:
prime.append(int(line))
num = int(line)
print("!! load end !!\n")
file_data.close()
prm_cnt = len(prime)
####################################################################
#Function Description:A function that flags a prime number when it is found
#Arg1:Number to judge whether it is a prime number Divide by the prime numbers that have appeared so far and check if there is a remainder
#Arg2:Number of prime numbers discovered so far
#Arg3:List of prime numbers can be referenced from outside the function
#Return:Primality test FLAG
####################################################################
def prime_func(num ,prm_lp, prm ):
cnt = 0
ret = "FALSE"
for j in range(0,prm_lp):
rem = num % prm[j]
if rem == 0:
cnt = 1#FALSE
break
if cnt == 0:
prm_lp = prm_lp + 1#Count new prime numbers and increase the number of divisions for finding the next prime number by 1.
prm.append(num)#Add new prime number to list
ret = "TRUE"
return ret
####################################################################
#Function Description:Prime number search
####################################################################
def calc_prime():
global prime
global prm_cnt
global num
pfile = 'prime.txt'
E_OK = "TRUE"
out_file = open(pfile,'a')
while 1 :
num = num + 2 #Search by 2 because there are only prime numbers in odd numbers
ret = prime_func(
num, #Number to judge whether it is a prime number
prm_cnt, #Number of prime numbers
prime #List of prime numbers
)
if E_OK == ret: #Prime number discovery
print(str(prime[len(prime)-1]) )
prm_cnt = prm_cnt + 1
out_file.write(str(num) + "\n")
out_file.close()
####################################################################
#Function Description:main function
####################################################################
def Main():
load_prime()
calc_prime()
if __name__=="__main__":
Main()
Recommended Posts