diff --git a/src/algorithms/math/fast-powering/__test__/fastPowering.test.js b/src/algorithms/math/fast-powering/__test__/fastPowering.test.js index 0a5da7561a..ae8683dff2 100644 --- a/src/algorithms/math/fast-powering/__test__/fastPowering.test.js +++ b/src/algorithms/math/fast-powering/__test__/fastPowering.test.js @@ -19,5 +19,8 @@ describe('fastPowering', () => { expect(fastPowering(16, 16)).toBe(18446744073709552000); expect(fastPowering(7, 21)).toBe(558545864083284000); expect(fastPowering(100, 9)).toBe(1000000000000000000); + expect(fastPowering(5, -5)).toBe(0.0003200000000000002); + expect(fastPowering(-5, 5)).toBe(-3125); + expect(fastPowering(-5, -5)).toBe(-0.0003200000000000002); }); }); diff --git a/src/algorithms/math/fast-powering/fastPowering.js b/src/algorithms/math/fast-powering/fastPowering.js index 4f4a6b3571..a7d56c339e 100644 --- a/src/algorithms/math/fast-powering/fastPowering.js +++ b/src/algorithms/math/fast-powering/fastPowering.js @@ -14,6 +14,12 @@ export default function fastPowering(base, power) { return 1; } + if (power < 0) { + const powerNext = power * -1; + const baseNext = 1 / base; + return fastPowering(baseNext, powerNext); + } + if (power % 2 === 0) { // If the power is even... // we may recursively redefine the result via twice smaller powers: