python - Why does this prime test work? -
i have found python function testing whether or not number prime; however, cannot figure out how algorithm works.
def isprime(n): """returns true if n prime""" if n == 2: return true if n == 3: return true if n % 2 == 0: return false if n % 3 == 0: return false = 5 w = 2 while * <= n: if n % == 0: return false += w w = 6 - w return true
let's start first 4 lines of function's code:
def isprime(n): if n == 2: return true if n == 3: return true if n % 2 == 0: return false if n % 3 == 0: return false
the function tests see if n
equal 2 or 3 first. since both prime numbers, function return true
if n
equal either.
next, function tests see if n
divisible 2 or 3 , returning false
if either true. eliminates extremely large amount of cases because half of numbers above 2 not primes - divisible 2. same reason applies testing divisibility 3 - eliminates large number of cases.
the trickier part of function in next few lines:
i = 5 w = 2 while * <= n: if n % == 0: return false += w w = 6 - w return true
first, i
(or index) set 5. 2 , 3 have been tested, , 4 tested n % 2
. so, makes sense start @ 5.
next, w
set 2. w
seems "incrementer". now, function has tested numbers (n % 2
), faster increment 2.
the function enters while
loop condition i * <= n
. test used because every composite number has proper factor less or equal square root. wouldn't make sense test numbers after square root because redundant.
in while
loop, if n
divisible i
, not prime , function returns false
. if not, i
incremented "incrementer" w
, which, again, faster.
perhaps trickiest part of function lies in second-to-last line: w = 6 - w
. causes "incrementer" w
toggle between values 2 , 4 each pass through loop. in cases w
4, bypassing number divisible 3. faster remaining @ 2 because function tested divisibility both 2 , 3.
finally, function returns true
. if function hasn't detected cases n
divisible something, must prime number.
Comments
Post a Comment