Reputation: 3706
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.
Upvotes: 1
Views: 3568
Reputation: 224922
One number AND another is the bits of one number masked by the bits of another number. If a number AND 1 is 0 (not n & 1
would be True
), that means it's divisible by two, since all multiples of 2 have a 0 as the rightmost binary digit.
11 = 00001011 (Not divisible by 2) 28 = 00011100 (Divisible by 2)
& 1 = 00000001 & 1 = 00000001
--------------- ---------------
00000001 00000000
Upvotes: 7
Reputation: 559
For example,
12 & 7 = 1100 & 0111 = 0100 = 4
For the isPrime function, the first condition checks whether it is 0 or 1. The second condition checks whether it is 2. The third condition then checks if (n&1), which is a check whether the number is even. Every even number when converted to binary form has 0 in its last digit. So for example,
14 & 1 = 1110 & 0001 = 0
14 is proved to be even and henceforth not prime.
Upvotes: 0