A prime number is a number that's only divisible by 1 and itself. The method it's using is to try dividing your candidate number n
by every other number from 2 up to itself; however if any number i
is a divisor of your number n
then so is n / i
and at least one of them is less than or equal to sqrt(n)
therefore we need only test up to sqrt(n)
inclusive. In practice we need only test the divisors that are actually prime themselves but since we don't have a list of primes to hand we'll test every one.
what in the above
i
is? and why it got a 2 starting value?
i
is the potential factor of n
we're testing. It starts with 2 because we don't care if 1 divides n
(and trivially it will) because the prime definition allows / expects that.
what is the i = i + 1 statement, in this concrete example for? Can't see its use in the program.
It's incrementing the i
value at the end of the loop defined by the while i <= sqrt(n)
; it means we advance i
to test the next candidate divisor of n
.
and finally, how python knows when to print 'is a prime number.' although it is out of the body loop?
We initialise msg
to "is a prime number" and if we find any divisor then we change it to "is not a prime number" inside the loop. If the loop doesn't find a divisor, or if the loop never runs, we'll use the initial value we set which is "is a prime number". Incidentally you could break
out of the loop when you find a divisor; there's no point carrying on the test after that.
As another aside you probably want to compute sqrt(n)
outside the while and store than in a variable to use in the while
- you may be recalculating the square root for every iteration, which is relatively expensive.