问题
def is_prime(number):
for i in range(2, number):
if number % 1 == 0 and number % i == 0:
return False
else:
return True
print(is_prime(13))
print(is_prime(55)) #True ##Why ???
def prime_numbers(a, b):
lst = []
for i in range(a,b+1):
if is_prime(i):
lst.append(i)
return lst
print(prime_numbers(50, 100))
This is my code and suppose I have prime_numbers(50, 100)
.
It should return [53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
instead of
[51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
.
So what is wrong with my code ?
回答1:
Relocate the return True
line:
def is_prime(number):
for i in range(2, number):
if number % 1 == 0 and number % i == 0:
return False
return True
print(is_prime(13)) # True
print(is_prime(55)) # False
Your code isn't working because you return True
or False
during the first iteration.
来源:https://stackoverflow.com/questions/23079761/find-prime-numbers-in-range