We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents abb7bb4 + 374c424 commit dc02fd3Copy full SHA for dc02fd3
Maths/BinaryExponentiationRecursive.js
@@ -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