Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
6 changes: 6 additions & 0 deletions src/algorithms/math/fast-powering/fastPowering.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down