[Algorithm] Calculate Pow(x,n) using recursion
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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)
以上是关于[Algorithm] Calculate Pow(x,n) using recursion的主要内容,如果未能解决你的问题,请参考以下文章