I know it’s been discussed many times; I’ve read it, but somehow I can’t get it.
I want to write a program that determines if the entered number is prime or not.
One of the implementations I found somewhere on the Internet:
from math import *
def main():
n = abs(input("Enter a number: "))
i = 2
msg = 'is a prime number.'
while i <= sqrt(n):
if n % i == 0:
msg = 'is not a prime number.'
i = i + 1
print n, msg
main()
A couple of questions here:
- In the above, what is
i, and why does it have a starting value of2? - What does
i = i + 1do in this program? - How does the interpreter know when to print
'is a prime number.'even though it is out of the body loop?
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
nby every other number from 2 up to itself; however if any numberiis a divisor of your numbernthen so isn / iand at least one of them is less than or equal tosqrt(n)therefore we need only test up tosqrt(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.iis the potential factor ofnwe’re testing. It starts with 2 because we don’t care if 1 dividesn(and trivially it will) because the prime definition allows / expects that.It’s incrementing the
ivalue at the end of the loop defined by thewhile i <= sqrt(n); it means we advanceito test the next candidate divisor ofn.We initialise
msgto “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 couldbreakout 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 thewhile– you may be recalculating the square root for every iteration, which is relatively expensive.