Skip to content

Commit dc02fd3

Browse files
authored
Merge pull request TheAlgorithms#336 from c-utkarsh/add-binary-expo-recursive
Added Binary Exponentiation (Recursive)
2 parents abb7bb4 + 374c424 commit dc02fd3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Modified from:
3+
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py
4+
5+
Explaination:
6+
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
7+
*/
8+
9+
const binaryExponentiation = (a, n) => {
10+
// input: a: int, n: int
11+
// returns: a^n: int
12+
if (n === 0) {
13+
return 1
14+
} else if (n % 2 === 1) {
15+
return binaryExponentiation(a, n - 1) * a
16+
} else {
17+
const b = binaryExponentiation(a, n / 2)
18+
return b * b
19+
}
20+
}
21+
22+
const main = () => {
23+
// binary_exponentiation(2, 10)
24+
// > 1024
25+
console.log(binaryExponentiation(2, 10))
26+
// binary_exponentiation(3, 9)
27+
// > 19683
28+
console.log(binaryExponentiation(3, 9))
29+
}
30+
31+
main()

0 commit comments

Comments
 (0)