diff --git a/src/algorithms/math/fast-powering/__test__/fastPowering.test.js b/src/algorithms/math/fast-powering/__test__/fastPowering.test.js index 0a5da7561a..2dba98bd49 100644 --- a/src/algorithms/math/fast-powering/__test__/fastPowering.test.js +++ b/src/algorithms/math/fast-powering/__test__/fastPowering.test.js @@ -1,6 +1,15 @@ import fastPowering from '../fastPowering'; describe('fastPowering', () => { + it('should compute negative powers correctly', () => { + expect(fastPowering(2, -1)).toBe(0.5); + expect(fastPowering(2, -2)).toBe(0.25); + expect(fastPowering(2, -3)).toBe(0.125); + expect(fastPowering(4, -1)).toBe(0.25); + expect(fastPowering(5, -2)).toBeCloseTo(0.04, 10); + expect(fastPowering(10, -1)).toBe(0.1); + }); + it('should compute power in log(n) time', () => { expect(fastPowering(1, 1)).toBe(1); expect(fastPowering(2, 0)).toBe(1); diff --git a/src/algorithms/math/fast-powering/fastPowering.js b/src/algorithms/math/fast-powering/fastPowering.js index 4f4a6b3571..9d566d830b 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) { + // Negative power means we need to compute the reciprocal. + // x^(-n) = 1 / x^n + return 1 / fastPowering(base, -power); + } + if (power % 2 === 0) { // If the power is even... // we may recursively redefine the result via twice smaller powers: