Skip to content

Instantly share code, notes, and snippets.

@chrismilson
Last active August 6, 2020 01:33
Show Gist options
  • Save chrismilson/c252b4fb6243b3005f37dac42da303bf to your computer and use it in GitHub Desktop.
Save chrismilson/c252b4fb6243b3005f37dac42da303bf to your computer and use it in GitHub Desktop.
Interview Question

Power of a Power

Write a program to determine whether a number, n, is a power of 2k.

clarification: n, k ≥ 0

Follow up: Can you do it with O(1) time and space complexity?

Examples

Input: n = 512, k = 3

Output: True

Explanation: 23 = 8 and 83 = 512.

Input: n = 1024, k = 4

Output: False

Explanation: 24 = 16, and 1024 is not a power of 16.

Solution

Brute Force

We can calculate 2k and then multiply it by itself multiple times, checking whether the current power is the number we are looking for.

def powerOfPower(n, k):
    ## the same as 2 ** k, potentially faster
    base = 1 << k
    curr = 1
    while curr < n:
        curr *= base
        if curr == n:
            return True
    return False

Time Complexity: O(log n); the variable curr grows exponentially.

Space Complexity: O(1).

Maths

We can determine whether or not a number is a power of two very quickly using bitwise operators:

def powerOfTwo(n):
    return n != 0 and n & n - 1 == 0

The trick, n & n - 1, gives us a number, n', which is n with its least significant bit removed. If n is a power of two, it will only have one bit, and so n' will be 0.

The next part comes from the following fact:

equation

And numbers that are not powers of 2k, namely 2m·k + i for 1 ≤ i < k will have:

equation

Leading us to our final implementation:

def powerOfPower(n, k):
    if n == 0:
        return False
    if n & n - 1 != 0:
        return False
    return n % (1 << k) - 1 == 1

Time Complexity: O(1).

Space Complexity: O(1).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment