Question

I've been trying to make a prime number generator in Python, basically porting this Scratch project into Python terms, and then writing the primes into a text document.

For some reason though, it isn't working and I can't work out why, as it is just writing the numbers as it 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 so far")
        j = j + 1
    print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
    f.close
    return(" ")

So, the program asks the user for how many primes it should generate, and it should then repeat from k=2 to j = j+1 until that number of primes is reached.

Also, if possible, I should like the commented out IF statement to work, as when that was included it repeated what prime number it was on several times. EDIT: adding what happens when run

how many primes? 1500
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
There have been 1000 primes counted so far
Primes written to file 'primes.txt', 1500 written
Was it helpful?

Solution

Use while not(k==j) and not(j%k==0): in place of while not(k==j) or not(j%k==0): Then it will work fine.

I hope this is the code you are 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) and 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 so far")
        j = j + 1
    print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
    f.close
    return(" ")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top