Find prime numbers in range

坚强是说给别人听的谎言 提交于 2019-12-25 02:26:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!