二进制与运算说明

2024-04-25 08:58:13 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下位、二进制和运算符的用途以及如何使用它吗?我正在研究生成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

我也看了看Python Bitwise Operators Example,但抓不住。在


Tags: andthefalsetrueonlyreturnifis
2条回答

例如

12和7= 1100和0111 =0100 =4个

对于isPrime函数,第一个条件检查它是0还是1。第二个条件检查它是否为2。第三个条件检查是否(n&1),即检查数字是否为偶数。每一个偶数在转换为二进制形式时,其最后一位数字为0。例如

14和1= 1110和0001 =0

从现在开始,14也不是质数。在

一个数和另一个数是一个数的位被另一个数的位所掩盖。如果一个数字和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

相关问题 更多 >

    热门问题