Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if n is divisible by power of 2 without using arithmetic operators in Python
When we need to check if a number is divisible by a power of 2 without using arithmetic operators, we can use bitwise operations. This approach leverages the binary representation of numbers and bit manipulation.
Problem Understanding
Given two numbers x and n, we need to check whether x is divisible by 2n without using division, modulo, or other arithmetic operators. For example, if x = 32 and n = 5, we check if 32 is divisible by 25 = 32.
Algorithm
The key insight is that a number is divisible by 2n if and only if its last n bits are all zeros. We can check this using bitwise AND operation ?
- Create a mask with n ones: (2n - 1)
- Perform bitwise AND between x and the mask
- If result is 0, then x is divisible by 2n
Implementation
def solve(x, n):
if (x & ((1 << n) - 1)) == 0:
return True
return False
# Test cases
x = 32
n = 5
print(f"Is {x} divisible by 2^{n}? {solve(x, n)}")
x = 16
n = 3
print(f"Is {x} divisible by 2^{n}? {solve(x, n)}")
x = 15
n = 2
print(f"Is {x} divisible by 2^{n}? {solve(x, n)}")
Is 32 divisible by 2^5? True Is 16 divisible by 2^3? True Is 15 divisible by 2^2? False
How It Works
Let's break down the bitwise operations ?
def solve_with_explanation(x, n):
# Create mask: (1 << n) - 1 gives us n ones
mask = (1 << n) - 1
print(f"x = {x}, binary: {bin(x)}")
print(f"2^{n} = {1 << n}, binary: {bin(1 << n)}")
print(f"mask = {mask}, binary: {bin(mask)}")
# Bitwise AND with mask
result = x & mask
print(f"x & mask = {result}, binary: {bin(result)}")
return result == 0
# Example with x = 32, n = 5
print("Example 1:")
print(solve_with_explanation(32, 5))
print()
# Example with x = 15, n = 2
print("Example 2:")
print(solve_with_explanation(15, 2))
Example 1: x = 32, binary: 0b100000 2^5 = 32, binary: 0b100000 mask = 31, binary: 0b11111 x & mask = 0, binary: 0b0 True Example 2: x = 15, binary: 0b1111 2^2 = 4, binary: 0b100 mask = 3, binary: 0b11 x & mask = 3, binary: 0b11 False
Alternative Compact Version
def is_divisible_by_power_of_2(x, n):
return (x & ((1 << n) - 1)) == 0
# Test the function
test_cases = [(32, 5), (16, 3), (15, 2), (64, 6), (100, 2)]
for x, n in test_cases:
result = is_divisible_by_power_of_2(x, n)
print(f"{x} divisible by 2^{n}? {result}")
32 divisible by 2^5? True 16 divisible by 2^3? True 15 divisible by 2^2? False 64 divisible by 2^6? True 100 divisible by 2^2? True
Conclusion
Using bitwise operations, we can efficiently check divisibility by powers of 2 without arithmetic operators. The key is creating a mask with n ones and checking if the last n bits of x are all zeros using bitwise AND.
