Skip to content

fix(math): handle negative powers in fast powering algorithm#2179

Open
fauzan171 wants to merge 1 commit into
trekhleb:masterfrom
fauzan171:fix/fast-powering-negative-power
Open

fix(math): handle negative powers in fast powering algorithm#2179
fauzan171 wants to merge 1 commit into
trekhleb:masterfrom
fauzan171:fix/fast-powering-negative-power

Conversation

@fauzan171
Copy link
Copy Markdown

Problem

The fastPowering function enters infinite recursion when called with a negative power value.

fastPowering(2, -1); // RangeError: Maximum call stack size exceeded
fastPowering(2, -2); // RangeError: Maximum call stack size exceeded

This happens because negative powers never hit the base case (power === 0) due to the floor division logic — Math.floor(-1 / 2) is -1, not 0.

Fix

Added handling for negative powers by computing the reciprocal before recursing:

x^(-n) = 1 / x^n

This converts the negative power to a positive one and computes the reciprocal.

Test Coverage

Added test cases for negative powers:

  • fastPowering(2, -1)0.5
  • fastPowering(2, -2)0.25
  • fastPowering(2, -3)0.125
  • fastPowering(4, -1)0.25
  • fastPowering(5, -2)0.04
  • fastPowering(10, -1)0.1

All existing tests continue to pass.

The fastPowering function previously entered infinite recursion when
called with a negative power value, since negative powers never hit
the base case (power === 0) due to the floor division logic.

Added handling for negative powers by computing the reciprocal:
x^(-n) = 1 / x^n, then recursively computing x^n with the positive
exponent.

Added test cases for negative powers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant