Complementing the other answers, it is also worth commenting that half of the iterations of
for i in range(1, number):
are useless. Note that no number is divisible by one greater than its half.
To understand better we will observe some things:
Any number divided by its half results in 2
.
That’s a fact: 10/5 = 2
, 20/10 = 2
, 14/7 = 2
etc. This implies that any number divided by another that is greater than its half results in a value less than 2
. 10/6 = 1.6
, 20/11 = 1.81
etc.
The only way a division can result in 1
is dividing a number by
himself
With these two absolute truths, we can move on to the mathematical language that, for any number x
:
>>> x/x = 1 #Um número dividido por ele mesmo resulta em 1
>>> x/(x/2) = 2 #Um número dividido pela sua metade resulta 2
and affirm with certainty that x
divided by any number y
such that x/2 < y < x
results in some value z
such that 1 < z < 2
. And none of them will be whole. Ie, We know by definition for these values, number % i != 0
will always return True
, it is therefore a waste of resources to test them.
it is interesting, then, that your for
be changed to:
for i in range(1, int(number/2)+1):
What should work for both even and odd numbers. Incidentally, it is worth remembering that no even number is prime (except for the 2
)
Take a look at How to generate 200,000 primes as fast as possible in Python? and Search containing primes
– Augusto Vasques