forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowLogarithmic.js
More file actions
Latest commit
26 lines (24 loc) · 966 Bytes
/
Copy pathPowLogarithmic.js
File metadata and controls
26 lines (24 loc) · 966 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import{isEven}from'./IsEven'
/**
* This algorithm is divide the n by 2 every time and pass this to recursive call to find the result of smaller result.
* why? Because
* x^n => [if n is even] x^(n / 2) * x^(n / 2) (example : 7^4 => 7^2 * 7^2)
* [if n is odd] x^(n / 2) * x^(n / 2) * x (example : 7^5 => 7^2 * 7^2 * 7)
* and repeat the above step until we reach to the base case.
*
* @function PowLogarithmic
* @description Given two integers x and n, return x^n in logarithmic complexity.
* @param {Integer} x - The input integer
* @param {Integer} n - The input integer
* @return {Integer} - Returns x^n.
* @see [Pow-Logarithmic](https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/)
*/
constpowLogarithmic=(x,n)=>{
if(n===0)return1
constresult=powLogarithmic(x,Math.floor(n/2))
if(isEven(n)){
returnresult*result
}
returnresult*result*x
}
export{powLogarithmic}