Check if given number is a power of d where d is a power of 2 in Python

Given a number n and another value d, we need to check whether n is a power of d, where d itself is a power of 2. For example, if n = 32768 and d = 32, the result is True because 32768 = 32³.

Algorithm

To solve this problem, we follow these steps:

  • First, check if n is a power of 2 using bitwise operations
  • Count how many times we can divide n by 2 to get the power of n as base 2
  • Count how many times we can divide d by 2 to get the power of d as base 2
  • Check if the power of n is divisible by the power of d

Implementation

def find_power_of_2(n):
    """Find the power of 2 for a given number"""
    return (1 + find_power_of_2(n // 2)) if (n > 1) else 0

def is_power_of_d(n, d):
    """Check if n is a power of d, where d is a power of 2"""
    # Check if n is a power of 2 using bitwise AND
    if n and (n & (n - 1)) == 0:
        # Count powers of 2 in n
        power_n = find_power_of_2(n)
        
        # Count powers of 2 in d
        power_d = find_power_of_2(d)
        
        # Check if power_n is divisible by power_d
        return power_n % power_d == 0
    
    return False

# Test the function
n = 32768
d = 32
result = is_power_of_d(n, d)
print(f"Is {n} a power of {d}? {result}")

# Additional examples
print(f"Is 64 a power of 8? {is_power_of_d(64, 8)}")   # 64 = 8²
print(f"Is 256 a power of 4? {is_power_of_d(256, 4)}") # 256 = 4?
Is 32768 a power of 32? True
Is 64 a power of 8? True
Is 256 a power of 4? True

How It Works

The algorithm works by:

  • Bitwise check: n & (n - 1) == 0 verifies if n is a power of 2
  • Power calculation: Recursively divides by 2 to count the power
  • Divisibility check: If power of n is divisible by power of d, then n is a power of d

Alternative Implementation

Here's a more efficient iterative approach:

import math

def is_power_of_d_optimized(n, d):
    """Optimized version using logarithms"""
    # Check if both n and d are powers of 2
    if n <= 0 or d <= 0 or (n & (n - 1)) != 0 or (d & (d - 1)) != 0:
        return False
    
    # Calculate powers using log base 2
    power_n = int(math.log2(n))
    power_d = int(math.log2(d))
    
    return power_n % power_d == 0

# Test the optimized function
n = 32768
d = 32
result = is_power_of_d_optimized(n, d)
print(f"Is {n} a power of {d}? {result}")
Is 32768 a power of 32? True

Conclusion

To check if n is a power of d (where d is a power of 2), verify both are powers of 2, then check if their logarithmic powers have a divisible relationship. The bitwise operation n & (n - 1) == 0 efficiently determines if a number is a power of 2.

Updated on: 2026-03-25T15:07:11+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements