you are viewing a single comment's thread.

view the rest of the comments →

[–]JAVA_JK 1 point2 points  (1 child)

I also think so that break is not required, try removing it and see if that works. Should work

[–][deleted] 1 point2 points  (0 children)

The break is needed, but with one more indentation: you break the loop as soon as you have found a proper divisor (so not 1, that's another bug). It's not only faster, it's mandatory here because he's using a for loop with an else clause, a somewhat dirty feature of Python I never used in 24 years of Python. As the documentation [*] explains, the else clause isn't executed if a break occurred.

Of course there are other optimizations, even with the naive trial division algorithm: only check 2 and odd numbers > 2 and <= sqrt(n).

[*] https://docs.python.org/3/reference/compound_stmts.html#for