首页 > 其他 > 详细

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

时间:2019-04-29 22:56:07      阅读:118      评论:0      收藏:0      [点我收藏+]

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)

 

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

原文:https://www.cnblogs.com/Answer1215/p/10793258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!