如何使用python

时间:2018-09-07 06:24:52

标签: python bitwise-operators

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

没有人知道plz建议的最佳方法。如果我输入的是26,那么它还会显示Divisible

#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 个答案:

答案 0 :(得分:1)

您可以使用模运算符%检查除数。这给出除法运算后的余数。例如,5%3将给出2,因为5/3是1的余数2。如果它可以被3整除,则该操作将不给出余数:

number = int(input('enter number: '))
if number % 3 == 0:
    print(number, 'is divisible by 3')
else:
   print(number, 'isn\'t divisible by 3')

我不建议使用裸露的int(input()),但为简单起见,我这样做了。您可能会使用try / except:

def int_input(prompt):
    while True:
        try:
            r = int(input(prompt))
        except ValueError:
            print('invalid entry')
        else:
           return r

然后将您的输入行替换为:

number = int_input('enter number: ')

注意:抱歉,此操作不使用位运算符

答案 1 :(得分:0)

检查给定数字是否可以被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")

答案 2 :(得分:0)

我们知道学校的原则:如果十进制数字的总和可被9整除,则数字可被9整除。
相同的方法适用于数字系统b和除数b-1的任何基数:对于base = 4,我们可以检查2位块的总和是否可被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)