如何在python中使用位运算符知道数字可被3或任何奇数整除
我从用户那里得到一个数字&我必须检查给定的数字是否可以被3整除 有人知道最好的方法吗。如果我的输入是26,那么它也显示出可除性如何在python中使用位运算符知道数字可被3或任何奇数整除,python,bitwise-operators,Python,Bitwise Operators,我从用户那里得到一个数字&我必须检查给定的数字是否可以被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) ): pr
#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')
检查给定数字是否可被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")
函数递归检查
#这个数字是否可以被17整除
def可分(n):
#如果n=0或n=17,则为是
如果(n==0或n==17):
返回真值
#如果n小于17,则不能被17整除
如果(n<17):
返回错误
#按楼层减少数量(n/16)
返回可分((int)(n>>4)-(int)(n&15))
#用于检查上述功能的驱动程序代码
n=12
如果(isDivisible(n)):
打印(n,“可被17整除”)
其他:
打印(n,“不能被17整除”)
我们知道学校的原则:如果十进制数字之和可以被9整除,那么数字就可以被9整除。
同样的方法适用于数字系统
b
和除数b-1
的任何基数:对于base=4,我们可以检查两个位块的总和是否可以被3整除。我们可以重复这个过程,直到除两位之外的所有位都变成零
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)
您应该首先告诉您的算法或您尝试了哪些方法但没有成功,只有这样,SO社区才会在您的代码出错的地方帮助您。在这里发布你的代码。开始了解为什么需要逐位运算符?从右侧开始计算非零奇数位和非零偶数位的数量。如果它们的差可以被3整除,那么这个数字就可以被3整除。你想纠正你的缩进吗?谢谢你的回答,但我想这是17的,我需要检查3的