How can I verify if a number n is divisible by x using bitwise operations?
I find lot of related links on this but I don't clearly understand them as they were not in Python. For example, what if I want to verify if 81 is divisible by 3, 9 or 4?
I want to use bitwise operations and I want to understand how to implement this using Python.
Bitwise operation as their name let guess operate on binary representation of numbers. That means that they will be highly efficient to test divisibility by a power or 2, but hardly usable for any other case.
Examples:
n & 1 == 0n & 3 == 0n & 7 == 0There are other divisibility rules that could be used: you could adapt the casting out 9 or 11 to test divisibility by 15 or 17 (base 16 uses to nibbles per byte), but as one single integer division is often faster than making many simpler operations (accumulator directly processes numbers of 32 or 64 bits) they are seldom used...
If your requirement is to test divisibility by 3 and 9, you could adapt casting out 9 for 3 = 4 - 1, and 11 for 9 =8+1. 81 = 0b1010001
You can code this easily with shifts (>>) and binary &
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With