我正在尝试编写一个程序,它将打印给定范围内的所有素数。我写了它,输出几乎没问题,它打印素数,但由于某种原因它打印4,这不是一个主要的... 任何助理都将非常感激!
def primes():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
num = 0
i = 0
ctr = 0
for num in range(start,end+1,1):
ctr = 0
for i in range(2,num//2,1):
if num % i == 0 :
ctr = ctr + 1
break
if (ctr==0 and num != 1):
print(num)
答案 0 :(得分:0)
for i in range(2,num//2,1):
让我们在num = 4时检查这段代码,它变为
for i in range(2,2,1):
现在我们看到了问题。 溶液..?
for i in range(2,(num//2)+1,1):
答案 1 :(得分:0)
以下方法都是可能用于在您的范围内检查的素数检查器:
def isPrime(Number): # slow
return 2 in [Number, 2 ** Number % Number]
def isprime(n): # out of memory errors with big numbers
"""check if integer n is a prime"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def is_prime(n): # Best until now
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
# print '\t', f
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
答案 2 :(得分:0)
MATCH (u:NodeType)
WITH u
ORDER BY u.Y DESC
WITH u.X AS X, collect(u) AS us
RETURN us[0] AS u
以上是错误的。您正在从for i in range(2,num//2,1):
迭代到2
您应该从num / 2 - 1
迭代到2
。 (sqrt(num)
)
或者,您可以对range(2, int(math.sqrt(n)) + 1)
进行特殊检查,并将范围修改为2