gpt4 book ai didi

python - 对于循环重复/卡住? Python 3.2

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:40 27 4
gpt4 key购买 nike

我正在尝试为埃拉托色尼筛法编写一个 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)

最佳答案

您的代码可以通过以下实现大大简化:

  • 最多 n 的数字可以根据需要轻松生成,它们不必预先计算并存储在列表中。

  • 2 是唯一的偶素数,所以你只需要测试奇数。

  • 所有数字都可以唯一地完全分解为质因式(这称为算术基本定理)。这意味着您需要尝试除以的唯一数字是您之前计算的素数 --- 所有其他数字都将至少被这些素数中的一个整除(或者它们本身就是素数)。

按照这些思路尝试一些事情:

stop = int(input("Enter number to calculate all primes up to: "))

primes = []

for n in range(3, stop, 2): # Step by two each time
was_prime = True # Needed to break out of nested loop
for p in primes:
if n % p == 0: # A prime divides n
was_prime = False
break # No need to continue
if was_prime:
primes.append(n)

print(primes) # You can insert the number 2 here if you like

另外,请注意间距和缩进。在 Python 中,当你的间距错误时,不仅难以阅读,而且会导致运行时错误。

关于python - 对于循环重复/卡住? Python 3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498621/

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