python - Basic Prime Number generator -
i've been trying make prime number generator in python, porting this scratch project python terms, , writing primes text document.
for reason though, isn't working , can't work out why, writing numbers goes.
def primenumbers(): j = 2 f = open("primes.txt", "w") primes = [] notprimes = [] ask = input("how many primes? ") while len(primes) < int(ask): k = 2 while not(k==j) or not(j%k==0): k = k + 1 if k == j: primes.append(j) f.write(str(j)+"\n") else: notprimes.append(j) # if len(primes)%1000 == 0: # print("there have been " + str(len(primes)) + " primes counted far") j = j + 1 print("primes written file 'primes.txt', " + str(len(primes)) + " written") f.close return(" ")
so, program asks user how many primes should generate, , should repeat k=2 j = j+1 until number of primes reached.
also, if possible, should commented out if statement work, when included repeated prime number on several times. edit: adding happens when run
how many primes? 1500 there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far there have been 1000 primes counted far primes written file 'primes.txt', 1500 written
use while not(k==j) , not(j%k==0):
in place of while not(k==j) or not(j%k==0):
work fine.
i hope code looking for:
def primenumbers(): j = 2 chk = 1 f = open("primes.txt", "w") primes = [] notprimes = [] ask = input("how many primes? ") while len(primes) < int(ask): k = 2 while not(k==j) , not(j%k==0): k = k + 1 if k == j: primes.append(j) f.write(str(j)+"\n") else: notprimes.append(j) if len(primes) >= 1000*chk: chk = chk + 1 print("there have been " + str(len(primes)) + " primes counted far") j = j + 1 print("primes written file 'primes.txt', " + str(len(primes)) + " written") f.close return(" ")
Comments
Post a Comment