[Algorithm] Calculate Pow(x,n) using recursion

Asking you to implement the Math.pow method

The navie implemenation can be:

// O(N)
const pow1 = (x, n) => {
  if (n === 0) {
      return 1;
  } else {
    return x * pow1(x, n - 1)
  }
}

console.log(pow1(2, 8))
// F(8) - (F7) - (F6) - (F5) - (F4) - (F3) - (F2) - (F0)

It takes O(N) time.

Now if we want to improve it to O(logN) time. we can do:

// O(logN)
const pow2 = (x, n) => {
  if (n === 0) {
    return 1;
  } 
  if (n % 2 === 0) {
      const y = pow2(x, n/2);
      return y * y;
  } else {
      return x * pow2(x, n-1);     
  }
}

console.log(pow2(2, 8))
// F(8) - (F4) - (F2) - (F1) - (F0)

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10793258.html
今日推荐