[Why does this] need a break in the for loop?
Let me quote this tutorial you might want to look at:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) [...], but not when the loop is terminated by a break statement.
This means that in your while
-loop,
primes.append(x)
a += 1
x += 2
is only executed if the for
-loop has iterated over all i in range(2, x)
and never once encountered break
. (This means, that there was no divisor of x found)
Without the break
statement the code above would be executed in every iteration of the while
-loop. Therefore, without the break
statement you just add 2
to x
every time you find a divisor of x and claim that x is prime as soon as you reach the end of range(2, x)
(note that in the range expression it's the original x
before you started adding 2
). This seems to work for small numbers but is not the same as checking if x has any divisors.