AlgoDaily 07: Power of Three

“Given an integer num, write a method to determine if it is a power of 3.”

console.log(powerOfThree(9));
// true

To calculate a power of x, we could keep multiplying by x until we hit the exponent.

That means to see if something is a power of x, we can do the reverse and keep diving by x until we hit 1 or a number that is not a multiple of 3.

E.g. for 9, we’d go 9, 3, 1 and identify it as a power of 3. For 12, we’d go 12, 4 and identify it as not a power of 3.

This has O(log3(n)) complexity.

function powerOfThree(x) {
	while (true) {
		x /= 3;
		if (x === 1) {
			return true;
		}
		if (x % 3 !== 0) {
			return false;
		}
	}
}

Test cases:

powerOfThree(9);
// true

powerOfThree(7);
// false

powerOfThree(729);
// true

powerOfThree(12);
// false

powerOfThree(15);
// false

Tech mentioned