所以首先,我意识到有更简单的方法来获得质数列表,但我这么做只是为了学习。我对这个问题的理解很差(正如你会看到的),所以如果这是一个愚蠢的问题,我很抱歉。我在努力学习。
#make an empty list to store primes in
primes = list()
#make a variable to easily change the amount of numbers I test for primality
high_val = 15
#Allocate a range that I will test all numbers in for primality
for n in range(2, high_val):
#Within the previous for loop, start another for loop to test every integer against every
#value inside the primes list
for p in primes:
if n % p == 0:
print(%s is not prime" % n)
else:
#If n is prime, I add it to the list and print that it is prime
primes.append(n)
print("%s is a prime" % n)我不知道这些评论是否会增加阅读难度,但这就是我的逻辑。该函数没有打印输出。所以我想,素数是没有价值的,我需要给它一些可以比较的东西。因此,我在紧跟在第一行之后的开头添加了一个primes.append(2),并将范围改为(3,high_val)...
如果我这样做,它最终会为每个数字打印大约5次,表明它是质数,然后再打印5条消息,说明它不是质数。很明显,我做了一些非常错误的事情,如果有人知道我错在哪里和/或如何修复这个问题,我将非常感激。谢谢!
发布于 2019-03-09 14:21:51
问题是你遗漏了一些标志:如果这个数字是质数,你就会在每次检查另一个数字时打印出来。你应该只在迭代完所有的素数后才打印出来。
关于这一点,可以考虑使用all
primes = [2]
high_val = 15
for n in range(3, high_val, 2):
if all(n % p == 0 for p in primes):
print(f"{n} is prime")
primes.append(n)
else:
print(f"{n} is not prime")附言:我没有测试它。
https://stackoverflow.com/questions/55074371
复制相似问题