From 374c424ee3ab8b7e26c1998ba230080a848a3356 Mon Sep 17 00:00:00 2001 From: utkarsh Date: Thu, 1 Oct 2020 22:41:59 +0530 Subject: [PATCH] Added Binary Exponentiation (Recursive) --- Maths/BinaryExponentiationRecursive.js | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Maths/BinaryExponentiationRecursive.js diff --git a/Maths/BinaryExponentiationRecursive.js b/Maths/BinaryExponentiationRecursive.js new file mode 100644 index 0000000000..0830f2bc64 --- /dev/null +++ b/Maths/BinaryExponentiationRecursive.js @@ -0,0 +1,31 @@ +/* + Modified from: + https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py + + Explaination: + https://en.wikipedia.org/wiki/Exponentiation_by_squaring +*/ + +const binaryExponentiation = (a, n) => { + // input: a: int, n: int + // returns: a^n: int + if (n === 0) { + return 1 + } else if (n % 2 === 1) { + return binaryExponentiation(a, n - 1) * a + } else { + const b = binaryExponentiation(a, n / 2) + return b * b + } +} + +const main = () => { + // binary_exponentiation(2, 10) + // > 1024 + console.log(binaryExponentiation(2, 10)) + // binary_exponentiation(3, 9) + // > 19683 + console.log(binaryExponentiation(3, 9)) +} + +main() pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy