[Algorithm] Calculate Pow(x,n) using recursion
Using ALGORITHM PoW recursion
2023-09-14 09:00:48 时间
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
- [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
- [Debug] Diagnose a Slow Page Using Developer Tools
- [NPM] Create a new project using the npm init <initializer> command
- [Jest] Automate your migration to Jest using codemods
- [TypeScript] Using Assertion to Convert Types in TypeScript
- [Node.js] Using ES6 and beyond with Node.js
- [Reactive Programming] Using an event stream of double clicks -- buffer()
- [AngularJS] Using the LocalForage library for offline storage with Angular
- [Tools] Using Webpack require.context to conditionally load file
- [Algorithms] Quicksort algorithm using TypeScript
- [React Native] Using the Image component and reusable styles
- [CSS3] Using CSS Combinators to Identify Siblings and Descendants in CSS
- [AngularJS] Using AngularJS's ngClass
- 成功解决xgboost.core.XGBoostError: b‘[14:48:08] 0 feature is supplied. Are you using raw Booster inter
- 异常检测 | 迁移学习《Anomaly Detection in IR Images of PV Modules using Supervised Contrastive Learning》