Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powerofTwo algorithm solution

Tags:

javascript

Below is my algo to check if number is a power of two. When I run this algo in test case "2" the answer is false. I want to know why it behaves this way ?

  var isPowerOfTwo = function(n) {
      if(n === 1){
         console.log("i came here");
         return true;     
      }
      if(n === 0){
         return false;   
      }
      if(n%2 === 0){
         console.log(n);
         n=n/2;
         console.log(n);
         isPowerOfTwo(n);   
      }   
      if(n%2 === 1){
         return false;   
      }
 };
like image 860
Mike Avatar asked Jun 08 '26 17:06

Mike


2 Answers

You're not returning the recursive call, and you're also changing n before the tests have finished - if n / 2 resolves to 1 then your reassignment of n will result in the bottom if statement running. Use else instead, and don't reassign n, simply pass n / 2 to the recursive call:

var isPowerOfTwo = function(n) {
  if (n === 1) return true;
  if (n === 0) return false;
  if (n % 2 === 0) return isPowerOfTwo(n / 2);
  else return false;
};
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));

Your if (n%2 === 1) return false; condition could result in another bug: what if the initial n was not an integer? Then the function would call itself forever, resulting in an overflow.

like image 147
CertainPerformance Avatar answered Jun 10 '26 09:06

CertainPerformance


Because 1 % 2 === 1 The "problem" is that in the third if you are changing the value of n and not returning any value so it will enter the last if too.

like image 40
A. Llorente Avatar answered Jun 10 '26 10:06

A. Llorente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!