From 226169a432a494953c1e344ecc22383745e928a9 Mon Sep 17 00:00:00 2001 From: Utkarsh Chaudhary Date: Thu, 1 Oct 2020 23:27:32 +0530 Subject: [PATCH] Added Modular Binary Exponentiation (Recursive) (#337) --- Maths/ModularBinaryExponentiationRecursive.js | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Maths/ModularBinaryExponentiationRecursive.js diff --git a/Maths/ModularBinaryExponentiationRecursive.js b/Maths/ModularBinaryExponentiationRecursive.js new file mode 100644 index 000000000..c30ed5f2a --- /dev/null +++ b/Maths/ModularBinaryExponentiationRecursive.js @@ -0,0 +1,31 @@ +/* + Modified from: + https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py + + Explaination: + https://en.wikipedia.org/wiki/Exponentiation_by_squaring +*/ + +const modularBinaryExponentiation = (a, n, m) => { + // input: a: int, n: int, m: int + // returns: (a^n) % m: int + if (n === 0) { + return 1 + } else if (n % 2 === 1) { + return (modularBinaryExponentiation(a, n - 1, m) * a) % m + } else { + const b = modularBinaryExponentiation(a, n / 2, m) + return (b * b) % m + } +} + +const main = () => { + // binary_exponentiation(2, 10, 17) + // > 4 + console.log(modularBinaryExponentiation(2, 10, 17)) + // binary_exponentiation(3, 9, 12) + // > 3 + console.log(modularBinaryExponentiation(3, 9, 12)) +} + +main()