Can someone please explain the purpose of the bitwise, Binary AND Operator( & ) and how to use it? I was looking at different ways of making a isprime
function and came across this.
def isprime(n):
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers (counts by 2's)
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
I also looked at Python Bitwise Operators Example but couldn't grasp it.
&
. It is not any faster than usingn % 2
and it is less clear. – wim Jan 18 '13 at 1:56all
function and a genex to replace the for loop. – wim Jan 18 '13 at 1:58