From cf0976529162023d7e95c37189d5e04af4e119c6 Mon Sep 17 00:00:00 2001 From: Yatin Date: Thu, 18 Nov 2021 22:58:53 +0530 Subject: [PATCH 1/2] Add PowLogarithmic in Math --- Maths/PowLogarithmic.js | 13 +++++++++++++ Maths/test/PowLogarithmic.test.js | 15 +++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 Maths/PowLogarithmic.js create mode 100644 Maths/test/PowLogarithmic.test.js diff --git a/Maths/PowLogarithmic.js b/Maths/PowLogarithmic.js new file mode 100644 index 0000000000..f2a444cfc5 --- /dev/null +++ b/Maths/PowLogarithmic.js @@ -0,0 +1,13 @@ +import { isEven } from './IsEven' + +// Returns the value of x to the power of n (x^n) +const powLogarithmic = (x, n) => { + if (n === 0) return 1 + const result = powLogarithmic(x, Math.floor(n / 2)) + if (isEven(n)) { + return result * result + } + return result * result * x +} + +export { powLogarithmic } diff --git a/Maths/test/PowLogarithmic.test.js b/Maths/test/PowLogarithmic.test.js new file mode 100644 index 0000000000..e432213f6e --- /dev/null +++ b/Maths/test/PowLogarithmic.test.js @@ -0,0 +1,15 @@ +import { powLogarithmic } from '../PowLogarithmic' + +describe('PowLogarithmic', () => { + it('should return 1 for numbers with exponent 0', () => { + expect(powLogarithmic(2, 0)).toBe(1) + }) + + it('should return 0 for numbers with base 0', () => { + expect(powLogarithmic(0, 23)).toBe(0) + }) + + it('should return the base to the exponent power', () => { + expect(powLogarithmic(24, 4)).toBe(331776) + }) +}) From 97eb8c82ad003a7d27d7dbadf9d0ca8df6271f91 Mon Sep 17 00:00:00 2001 From: Yatin Date: Thu, 18 Nov 2021 23:58:04 +0530 Subject: [PATCH 2/2] add description --- Maths/PowLogarithmic.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Maths/PowLogarithmic.js b/Maths/PowLogarithmic.js index f2a444cfc5..ff57d14ef7 100644 --- a/Maths/PowLogarithmic.js +++ b/Maths/PowLogarithmic.js @@ -1,6 +1,19 @@ import { isEven } from './IsEven' -// Returns the value of x to the power of n (x^n) +/** + * This algorithm is divide the n by 2 every time and pass this to recursive call to find the result of smaller result. + * why? Because + * x^n => [if n is even] x^(n / 2) * x^(n / 2) (example : 7^4 => 7^2 * 7^2) + * [if n is odd] x^(n / 2) * x^(n / 2) * x (example : 7^5 => 7^2 * 7^2 * 7) + * and repeat the above step until we reach to the base case. + * + * @function PowLogarithmic + * @description Given two integers x and n, return x^n in logarithmic complexity. + * @param {Integer} x - The input integer + * @param {Integer} n - The input integer + * @return {Integer} - Returns x^n. + * @see [Pow-Logarithmic](https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/) + */ const powLogarithmic = (x, n) => { if (n === 0) return 1 const result = powLogarithmic(x, Math.floor(n / 2))