Home > Blockchain >  Recursion is 4 but the expected output is 64
Recursion is 4 but the expected output is 64

Time:10-10

  let power2 = (x,n) => {
    if(n == 0) return 1;
    let temp = power2(x,n/2);
    if(n%2 == 1) return temp * temp * x;
    return temp*temp;
}
console.log(power2(4,3));

This method has less nodes and time complexity but its giving wrong output

CodePudding user response:

The problem with the original code was the fact that n / 2 will result in a real number when you need it to be treated as an integer. Bitwise operation are always performed on integers so n >> 1 will correctly yield an integer. The same goes with modulo which converts the number to an integer first that's why it worked correctly in your code.

let power2 = (x, n) => {
  if (n === 0) return 1;
  const temp = power2(x, (n >> 1));
  if (n % 2 === 1) return temp * temp * x;
  return temp * temp;
}
console.log(power2(4, 3));

CodePudding user response:

If you need custom integer power function, based on recursion, consider this snippet:

// Custom pow
const myPow = (n, i) => i > 0 ? myPow(n, i - 1) * n : 1;

// Test
console.log(myPow(4, 3));

  • Related