Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Power Of Three (Main Thread)

Here is the interview question prompt, presented for reference.

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

The method will be called as follows:

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

console.log(powerOfThree(7));
// false

Constraints

  • The given would be a non zero positive integer in the range between 1 and 2147483647
  • Expected space complexity : O(logn)
  • Expected time complexity : O(1)

You can see the full challenge with visuals at this link.

Challenges • Asked over 4 years ago by Anonymous

Jake from AlgoDaily Commented on Sep 13, 2019:

This is the main discussion thread generated for Power Of Three.

Anonymous Commented on Sep 13, 2019:

function powerOfThree(num) {
if (num % 3 !== 0){
return false;
} else if (num === 3){
return true;
} else if (num % 3 === 0){
return powerOfThree(num / 3)
}
}

function powerOfThree2(num) {
var i = num;
while (i % 3 === 0 && i !== 3){
i = i / 3;
}
if (i % 3 !== 0){
return false;
} else if (i === 3){
return true;
}
}

console.log(powerOfThree(7));
console.log(powerOfThree(729));

Anonymous Commented on Jan 04, 2020:

def powerof3(num):
while num>3:
num = num/3
if num==3:
return True
else:
return False

Anonymous Commented on Jul 13, 2020:

function powerOfThree(num) {
return !!Math.pow(num, 1/3);
}

Ahmed Magdy Seleem Commented on Jan 11, 2021:

function powerOfThree(num) {
if (num % 3 === 0) return true;
else return false;
}

Rudy Commented on Jan 13, 2021:

In the answer provided in the video if the number 1 is passed as an argument than it should be false not true. 1 is not a power of three.
Shouldnt the first return be false?

SNIPPET
//code from Video

function powerOfThree(num) {
  let currentQuotient = num; 
  if (currentQuotient === 1) {
    return true;
  }

  while (currentQuotient>0) {
    currentQuotient = currentQuotient /3; 
    if (currentQuotient === 1) {
       return true;
     } 
     }
       return false;
  }

console.log(powerOfThree(1));
Jake from AlgoDaily Commented on Jan 13, 2021:

Hey Rudy,

Don't forget that any number to the 0th power or exponent is 1 (30 = 1). As such, we handle this edge case first.

Then we separately solve from the idea that after dividing, we'll eventually have a quotient of 1.

Rudy Commented on Jan 13, 2021:

Yes you're right, got it thanks Jake!