0
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 ?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • possible duplicate of [isPrime Function for Python Language](http://stackoverflow.com/questions/15285534/isprime-function-for-python-language) – Martijn Pieters Apr 15 '14 at 09:33
  • But you return `True` far to eagerly. – Martijn Pieters Apr 15 '14 at 09:34
  • 1
    This has already been answered below, but I'd just add that there's no point in iterating over the range `(2, number)`. You only need to go as far as half of `number` as any number greater than that cannot divide evenly into `number`. I'd probably also make sure that `number` is an integer otherwise the `range` is likely to throw an error. – elParaguayo Apr 15 '14 at 09:38
  • 2
    Dont think number%1==0 is needed, it is always True. To make it more efficient only go upto square root of the number + 1 (1 added to make sure you go upto the next integer when sqrt returns a float) – haraprasadj Apr 15 '14 at 10:34

1 Answers1

2

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143