forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow.js
More file actions
Latest commit
65 lines (56 loc) · 2.03 KB
/
Copy pathPow.js
File metadata and controls
65 lines (56 loc) · 2.03 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @function powLinear
* @description - The powLinear function is a power function with Linear O(n) complexity
* @param {number} base
* @param {number} exponent
* @returns {number}
* @example - powLinear(2, 2) => 4 --> 2 * 2
* @example - powLinear(3, 3) => 27 --> 3 * 3 * 3
*/
constpowLinear=(base,exponent)=>{
if(exponent<0){
base=1/base
exponent=-exponent
}
letresult=1
while(exponent--){
// Break the execution while the exponent will 0
result*=base
}
returnresult
}
/**
* @function powFaster
* @description - The powFaster function is a power function with O(logN) complexity
* @param {number} base
* @param {number} exponent
* @returns {number}
* @example - powFaster(2, 2) => 4 --> 2 * 2
* @example - powFaster(3, 3) => 27 --> 3 * 3 * 3
*/
constpowFaster=(base,exponent)=>{
if(exponent<2){
// explanation below - 1
returnbase&&([1,base][exponent]||powFaster(1/base,-exponent))
}
if(exponent&1){
// if the existing exponent is odd
returnbase*powFaster(base*base,exponent>>1)// explanation below - 2
}
returnpowFaster(base*base,exponent/2)
}
/**
* 1 - Magic of short circuit evaluation (&&, ||)
* if the base is 0 then it returns 0 cause 0 is falsy
* if the base is not 0 then it's must be truthy. after that, it will be executed the right portion of the && (AND) operator
* Now it checks the exponent by the help array index, is it 0 or 1.
* if the exponent is not 0 or 1 it's definitely less than 0, and a negative number is not a valid index number so it returns "undefined"
* if the expression is undefined mean -> falsy, the || (OR) operator evaluates the right portion that is a recursive function.
*/
/**
* 2 - Play with right shift bitwise operator (>>)
* right shift with any odd numbers it returns the floor number instead of float.
* E.g. if the number is 5, after right shifting with 1 it's will give us 2, not 2.5
* cause the right shift formula is --> x >> y = |x| / 2^y
*/
export{powLinear,powFaster}