gpt4 book ai didi

python - 基本素数生成器

转载 作者:行者123 更新时间:2023-12-01 05:25:15 25 4
gpt4 key购买 nike

我一直在尝试用Python制作一个素数生成器,基本上是移植this将项目 Scratch 为 Python 术语,然后将质数写入文本文档。

但由于某种原因,它不起作用,我无法弄清楚为什么,因为它只是按其运行方式写入数字。

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

因此,程序会询问用户应生成多少个素数,然后应从 k=2 重复到 j = j+1,直到达到该素数数量。

此外,如果可能的话,我希望注释掉的 IF 语句能够工作,因为当包含该语句时,它会多次重复它所在的素数。编辑:添加运行时发生的情况

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

最佳答案

使用while not(k==j) and not(j%k==0):代替while not(k==j) or not(j%k ==0): 然后就可以正常工作了。

我希望这是您正在寻找的代码:

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

关于python - 基本素数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com