Skip to content

Commit 226169a

Browse files
authored
Added Modular Binary Exponentiation (Recursive) (#337)
1 parent 5e9e2a1 commit 226169a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
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_exp_mod.py
4+
5+
Explaination:
6+
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
7+
*/
8+
9+
const modularBinaryExponentiation = (a, n, m) => {
10+
// input: a: int, n: int, m: int
11+
// returns: (a^n) % m: int
12+
if (n === 0) {
13+
return 1
14+
} else if (n % 2 === 1) {
15+
return (modularBinaryExponentiation(a, n - 1, m) * a) % m
16+
} else {
17+
const b = modularBinaryExponentiation(a, n / 2, m)
18+
return (b * b) % m
19+
}
20+
}
21+
22+
const main = () => {
23+
// binary_exponentiation(2, 10, 17)
24+
// > 4
25+
console.log(modularBinaryExponentiation(2, 10, 17))
26+
// binary_exponentiation(3, 9, 12)
27+
// > 3
28+
console.log(modularBinaryExponentiation(3, 9, 12))
29+
}
30+
31+
main()

0 commit comments

Comments
 (0)