代码之家  ›  专栏  ›  技术社区  ›  Gajanan Kolpuke

在python[closed]中如何使用位运算符知道数字可被3整除或任何奇数整除

  •  -5
  • Gajanan Kolpuke  · 技术社区  · 8 年前

    我从用户那里得到一个数字&我必须检查给定的数字是否可以被3整除。

    有人知道最好的方法吗。如果我的输入是26,那么它也是可除的

    #Using bitwise operator
    print('Entered number is divisible by 3 or not: ')
    intNumber = int( input('Enter number: ') )
    
    if( intNumber > 0 ):
        if( 3 & (intNumber-1) ):
            print('Divisible')
        else:
            print('Not Divisible')
    else:
        print('Not is less than zero')
    
    3 回复  |  直到 8 年前
        1
  •  0
  •   MBo    8 年前

    我们知道学校的原则:如果小数位数之和可以被9整除,那么数字就可以被9整除。
    同样的方法适用于任何数字系统的基 b 和除数 b-1

    11dec = 1011bin: 
    10 + 11 = 101
    01 + 01 = 10 - not divisible
    
    21dec = 10101bin: 
    01 + 01 + 01 = 11 - divisible
    
    
    def divis3(x):
        while(x & (~3)):   # added more bitwiseness :) instead of (x > 3)
            sum = 0
            while (x):
                sum += x & 3  # extract two least significant bits
                x >>= 2       # shift value to get access to the next pair of bits
            x = sum
        return (x == 0 or x==3)
    
        2
  •  0
  •   Sachin    8 年前

    检查给定的数字是否能被17整除

     # function to check recursively if the
     # number is divisible by 17 or not
     def isDivisible(n):
     # if n=0 or n=17 then yes
     if (n == 0 or n == 17):
        return True
    # if n is less then 17, not divisible by 17
    if (n < 17):
        return False
    # reducing the number by floor(n/16)
    return isDivisible((int)(n >> 4) - (int)(n & 15))
    # driver code to check the above function
    n = 12
    if (isDivisible(n)):
       print(n,"is divisible by 17")
    else:
       print(n,"is not divisible by 17")