From ca26b76c4c34a4081064359f7c656c81ef8e685b Mon Sep 17 00:00:00 2001 From: farharamadhan2 Date: Mon, 4 Oct 2021 20:49:30 +0700 Subject: [PATCH 1/4] improve power function to receive negative exponents --- Maths/Pow.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Maths/Pow.js b/Maths/Pow.js index 555e652aa6..6a3b547a3d 100644 --- a/Maths/Pow.js +++ b/Maths/Pow.js @@ -2,8 +2,15 @@ const pow = (x, y) => { let result = 1 - for (let i = 1; i <= y; i++) { - result *= x + if (y>= 0) { + for (let i = 1; i <= y; i++) { + result *= x + } + } else { + for (let i = y; i < 0; i++) { + result *= x + } + result = 1 / result } return result } From f8e4331b8efb93dbf8dbceddbda3b11d5d496a66 Mon Sep 17 00:00:00 2001 From: farharamadhan2 Date: Mon, 4 Oct 2021 20:54:30 +0700 Subject: [PATCH 2/4] add test case for negative exponents --- Maths/test/Pow.test.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Maths/test/Pow.test.js b/Maths/test/Pow.test.js index f5760048eb..6f127d9ad6 100644 --- a/Maths/test/Pow.test.js +++ b/Maths/test/Pow.test.js @@ -12,4 +12,8 @@ describe('Pow', () => { it('should return the base to the exponent power', () => { expect(pow(24, 4)).toBe(331776) }) + + it('should return 0.25 for numbers with base 2 and exponent -2', () => { + expect(pow(2, -2)).toBe(0.25) + }) }) From b4de131ed1716f76de134223492d9d9e646ea206 Mon Sep 17 00:00:00 2001 From: farharamadhan2 Date: 2021年10月13日 20:53:22 +0700 Subject: [PATCH 3/4] Pow function optimization using exponentiation by squaring --- Maths/Pow.js | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/Maths/Pow.js b/Maths/Pow.js index 6a3b547a3d..944dbde41e 100644 --- a/Maths/Pow.js +++ b/Maths/Pow.js @@ -1,18 +1,11 @@ // Returns the value of x to the power of y const pow = (x, y) => { - let result = 1 - if (y>= 0) { - for (let i = 1; i <= y; i++) { - result *= x - } - } else { - for (let i = y; i < 0; i++) { - result *= x - } - result = 1 / result - } - return result + if (y < 0) return pow(1 / x, -y) + else if (y === 0) return 1 + else if (y === 1) return x + else if (y % 2 === 0) return pow(x * x, y / 2) + else if (y % 2 !== 0) return x * pow(x * x, (y - 1) / 2) } export { pow } From d344fbb375b9f3d2f27bd30c4a7ebe0a0a59b20f Mon Sep 17 00:00:00 2001 From: farharamadhan2 Date: 2021年10月13日 20:57:25 +0700 Subject: [PATCH 4/4] add wiki link --- Maths/Pow.js | 1 + 1 file changed, 1 insertion(+) diff --git a/Maths/Pow.js b/Maths/Pow.js index 944dbde41e..aaab073b70 100644 --- a/Maths/Pow.js +++ b/Maths/Pow.js @@ -1,4 +1,5 @@ // Returns the value of x to the power of y +// Exponentiation by squaring : https://en.wikipedia.org/wiki/Exponentiation_by_squaring const pow = (x, y) => { if (y < 0) return pow(1 / x, -y)

AltStyle によって変換されたページ (->オリジナル) /