Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - Implementation

In pseudocode

Here's the complete solution:


function isPowerOfTwo(n)
    if n  0 then
        return false
    while n > 1
        if n mod 2  0 then
            return false
        n := n / 2
    return true

Each division by 22 reduces nn. If at any point nn is odd (modulo 202 \neq 0), you know it's not a power of two. The loop runs at most log2(n)\log_2(n) times.