我正在写一个素数程序,我想要一个提示,它目前打印素数,除了从9和15开始可被3和5整除的数字,但不知何故准确计算20,也是5的倍数,不是素数。任何帮助赞赏。使用python 2,因为我使用的是没有网络连接的旧Vaio。
def main():
nums = [2]
dividend = 3
while i < 30:
if dividend % nuns[i] > 0:
print divided, 'is prime'
nums.append(dividend)
dividend = dividend + 1
if dividend % nums[i] == 0:
print divided, 'is not prime'
nums.append(dividend)
dividend = dividend + 1
i = i + 1
main()
答案 0 :(得分:2)
您的代码不起作用,因为您只检查dividend
是否可以被nums
中的 i 号码整除。您需要检查它是否可被以前的素数的任何整除。 (在你的代码逻辑中还有其他问题 - 它在每个循环中检查两次素数,这恰好使它看起来可能是半工作的,而实际上它根本不起作用......)
为此,您需要使用嵌套循环 - Python tutorial显示如何使用嵌套的for
循环解决此问题。
或者,使用带有列表推导的any
函数来替换内部循环。
def get_primes(max):
""" Prints all prime numbers between 3 and max """
primes = [2]
for n in range(3, max + 1):
if any(n % p == 0 for p in primes):
print n, "is not prime"
else:
print n, "is prime"
primes.append(n)
get_primes(30)
答案 1 :(得分:1)
def primes(num):
if num == 2:
print("prime")
return True
more code here...
我假设你想要第一个甚至得到2作为素数。不要打扰模数只检查输入是否为2然后编写代码来检查其余部分。
编辑:以下代码将查找其给定范围内的所有素数,并将它们附加到名为primes
的列表中。它在Pyhton 3中,但你唯一需要改变的是打印语句:
primes = []
def is_prime(num):
if num == 1:
return False
if num == 2:
return True
for i in range(2, num):
if num % i == 0:
return False
return True
for i in range(1, 31):
if is_prime(i):
print(str(i) + " is prime.")
primes.append(i)
else:
print(str(i) + " is not prime.")
print("primes = " str(primes))
输出:
1 is not prime.
2 is prime.
3 is prime.
4 is not prime.
5 is prime.
6 is not prime.
7 is prime.
8 is not prime.
9 is not prime.
10 is not prime.
11 is prime.
12 is not prime.
13 is prime.
14 is not prime.
15 is not prime.
16 is not prime.
17 is prime.
18 is not prime.
19 is prime.
20 is not prime.
21 is not prime.
22 is not prime.
23 is prime.
24 is not prime.
25 is not prime.
26 is not prime.
27 is not prime.
28 is not prime.
29 is prime.
30 is not prime.
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]