-3

Can someone please explain why number 2 is also added to the list of prime numbers in the code below?

As the function below should only recognize a number as prime when there is at least 1 number with modulus not equal to 0.

As

2 % 0 = 0
2 % 1 = 0

That is why it should not be included, right?

def isprime(num1):
    for i in range(2, num1):
        if (num1 % i) == 0:
            return False
    return True


def getprimes(max_number):
    list_of_primes = []
    for i in range(2, max_number):
        if isprime(i):
            list_of_primes.append(i)
    return list_of_primes


def main():
    max_num_to_check = int(input('Enter the max limit: '))
    list_of_primes = getprimes(max_num_to_check)

    for i in list_of_primes:
        print(i)


main()
s3icc0
  • 41
  • 1
  • 7
  • 6
    Well, 2 _is_ a prime number.... – tobias_k Jan 27 '17 at 22:56
  • sorry tobias - but that is something that I am aware of - my question is related to the code – s3icc0 Jan 27 '17 at 22:58
  • 4
    "As the function below should only recognize a number as prime when there is at least 1 number with modulus not equal to 0" Where do you read this from your code? The code (correctly) checks whether there is _no_ number with modulo equal to 0, which is the case for 2 (although it will not even check modulus 0 and 1, as the range starts at 2) – tobias_k Jan 27 '17 at 23:00
  • 1
    It's always good to remember that `range()` yields a right-side open interval. – dhke Jan 27 '17 at 23:08
  • 2 is a prime number. – Frogboxe Jan 28 '17 at 18:30

1 Answers1

0

As the function below should only recognize a number as prime when there is at least 1 number with modulus not equal to 0

It seems like you misunderstood how the prime check works. The isprime method actually checks whether there is no number with a modulus equal to zero. Also, it only checks relevant numbers, and that does not include 0 and 1, since the modulus of any number with 1 is zero, and the modulus with 0 is actually not defined.

In the case of 2, the function will check all numbers in range(2, 2), which is empty, thus it (correctly) returns True. The function could be rewritten to this, maybe that's clearer:

def isprime(num1):
    return not any((num1 % i) == 0 for i in range(2, num1))
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • that was the lead I needed, thanks the problem I have with understanding code is that I dont pay enough attention to things like return and break - so for me I was always seeing 2 % 2 == 0 therefore return True ... but what it actually does is the condition is True therefore it steps a level above and return True ... – s3icc0 Jan 27 '17 at 23:11