我试图在用户选择的范围内找到每个素数,列出并计算它们。我的代码计数和列表编号不是素数。我真的找不到原因?有人可以帮助我。
print("This code will count how many prime number exist in a certain range")
count = 0
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
prime = []
for num in range(lower, upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
break
print(prime)
print("There are", len(prime), "prime number between", lower, "and", upper)
答案 0 :(得分:1)
你的素数部分是错误的。我将把它抽象为另一种方法以使其更容易。要成为素数,n%x
必须支持任何x
,x
位于数字[2,ceil(sqrt(n))]
中。
确保import math
def is_prime(num):
for i in range(2, math.ceil(num**(1/2))):
if num%i==0:
return False
return True
然后,只需替换
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
break
使用,
if num>1:
if is_prime(num):
prime.append(num)
答案 1 :(得分:1)
你的问题是你不要等所有分区检查将数字附加到素数列表:
if (num % i) == 0:
break
else:
prime.append(num)
break
代码修复:
is_prime =True
for i in range(2,num):
if num % i == 0:
is_prime = False
break
if is_prime:
prime.append(num)
$ python prime_test.py
This code will count how many prime number exist in a certain range
Enter lower range: 12
Enter upper range: 20
[13, 17, 19]
('There are', 3, 'prime number between', 12, 'and', 20)
答案 2 :(得分:1)
问题出在这里,
for i in range(2,num):
if (num % i) == 0: #If num is divisible by SOME i, it is not prime. Correct.
break
else: #If num is not divisible by SOME i, it is not prime. WRONG.
prime.append(num)
break
您应该检查这样的条件:If num is not divisible by ANY i, it is prime
。
使用for,
进行最少的更改 for i in range(2,num):
if (num % i) == 0:
break
else:
prime.append(num)
答案 3 :(得分:0)
这是从列表中获取素数的解决方案。向用户询问应创建素数之间的范围,并将其存储在list
中:
list4=list(range(3,10,1))
prime_num=[x for x in list4 if x%2!=0 and x%3!=0]