简体   繁体   English

基本素数生成器

[英]Basic Prime Number generator

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. 我一直在尝试用Python创建质数生成器,基本上是将这个 Scratch项目移植到Python术语中,然后将质数写入文本文档中。

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. 因此,程序会询问用户应生成多少个素数,然后应从k = 2重复到j = j + 1,直到达到该素数为止。

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. 另外,如果可能的话,我希望注释掉的IF语句起作用,因为当包含该语句时,它重复了几次素数。 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

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. 使用while not(k==j) and not(j%k==0):代替while not(k==j) or not(j%k==0):这样就可以正常工作。

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(" ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM