Cri*_*spy 0 python bitwise-operators
有人可以解释按位,二进制 AND 运算符( & )的目的以及如何使用它?我正在研究创建isprime函数的不同方法并遇到了这个问题。
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
Run Code Online (Sandbox Code Playgroud)
我还查看了Python 按位运算符示例,但无法掌握。
一个数和另一个数是一个数的位被另一个数的位掩蔽。如果一个数 AND 1 是 0(not n & 1将是True),这意味着它可以被 2 整除,因为 2 的所有倍数都有一个 0 作为最右边的二进制数字。
11 = 00001011 (Not divisible by 2) 28 = 00011100 (Divisible by 2)
& 1 = 00000001 & 1 = 00000001
--------------- ---------------
00000001 00000000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1462 次 |
| 最近记录: |