pHalyard
pHalyard

Reputation: 21

why does this evaluate 2 as prime?

I've looked for the answer but not found it hence this question. I am confused by the following code from the python documentation (4.4 of tutorial) on the break statements. the code works fine, but why is 2 found to be a prime number? At at the first run it seems that n % x would be 2 % 2 == 0? What am I missing about how the ranges iterate?

for n in range(2, 100):
    for x in range (2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        print(n, 'is prime')

other simlar code first excludes 2 as it is a 'special' prime and I cannot figure out how this code gets away with not doing that.

Upvotes: 2

Views: 83

Answers (2)

khelwood
khelwood

Reputation: 59146

If n is 2, then 2 is not in range(2, n). It is an empty range.

range(a,b) runs through integers that are greater than or equal to a, and strictly less than b.

In your program, the statement

if n % x == 0:
    ...

is in a loop that is being run for each x in the given range. If the range is empty, the loop is executed zero times, so no factors are checked.

Upvotes: 3

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31173

The range() considers first limit as inclusive, but the second one as exclusive. Therefore when the first iteration runs range(2, 2) doesn't return any elements. Therefore no checks are done and 2 is deemed prime.

Upvotes: 1

Related Questions