我正在尝试为埃拉托色尼筛子编写一个 python 脚本。我已经完成了所有工作,但是当我告诉程序测试每个数字是否是 √ 输入下方的至少一个素数的倍数时。它运行良好,但是当我尝试删除一个倍数时,它一直有效,直到它尝试删除 6 两次......我一直在查看我的代码,但似乎无法找出原因。我对 Python 很陌生,所以非常感谢您的帮助!--- 请注意,由于 SOF 制作代码块的方式,我的代码间距已关闭:
import math, os, threading
global iswhole
global tdprime
def iswhole(x):
if x%1 == 0:
return True
else:
return False
def tdprime(x):
prime = True
n = 2
while n < x:
if iswhole(x/n) == True:
return False
prime = False
n = x
else:
n += 1
if prime == True:
return True
number = 0
while number != 1:
number = int(input("Enter number to calculate all primes up to: "))
number_range = range(1,number+1)
sqrt = math.sqrt(number)
rsqrt = round(sqrt)
thelist = []
tsl = []
for num in range(1,rsqrt):
if tdprime(num) == True:
tsl.append(num)
tsl.remove(1)
for x in number_range: ## Making the List
thelist.append(x)
## Note it's " Key: Value " in dictionaries
print(tsl)
print("thelist: ",thelist)
print("Square root of input = ",sqrt)
print("Rounded Square root of input = ",rsqrt)
print()
for x in thelist: ## Testing each number in thelist
multiple = False
for y in tsl: ## Each prime number under √number
if iswhole(x/y):
print(x) ## If the current number in thelist divided by one of the prime numbers under √number is a whole
thelist.remove(x)## Remove the current number which isn't a prime
thelist.sort()
multiple = True ## Make multiple true so it doesn't print (could remove the multiple stuff and other if function, kind of pointless function now)
if multiple == False:
print("Prime! ",x)
print(thelist)