Since power of four means a number obtained by multiplying 4 by itself a number of times we can try the reverse operation (divide by 4.0).
We will start with the given number & loop until it's less than 1. Then if it's exactly 1 it means that this number is a power of four.
Otherwise it's not a power of four.
def is_power_of_four(num) while num > 1 num /= 4.0 end num == 1.0 end
Notice that we need to divide by 4.0 & not just 4 for this to work.
Since we keep dividing by 4 the time complexity should be
We can use a logarithm to check if the number is a power of another.
We will use our programing language Math module to compute the logarithm & then check if it's a whole numbers (no decimal).
def is_power_of_four(num) return false if num == 0 return false if num < 0 log = Math.log(num.abs, 4) log == log.round end
Same as our first approach, but since this is implemented by programing language it will probably perform better.