Skip to content

StorageMath.RootN returns one less than the exact root of a perfect power for short and int: RootN((short)15625, 6) is 4, RootN(1280000000, 7) is 19 #557

Closed

Description

@matt-edmondson

What's wrong

StorageMath.RootN gives a floor one too low for some exact powers in short and int. Each expected value below was checked against a BigInteger floor-root:

Call Actual Expected
StorageMath.RootN((short)15625, 6) 4 5 (5⁶ = 15625)
StorageMath.RootN((short)16384, 7) 3 4 (4⁷ = 16384)
StorageMath.RootN(893871739, 7) 18 19 (19⁷)
StorageMath.RootN(1280000000, 7) 19 20 (20⁷)
StorageMath.RootN(1801088541, 7) 20 21 (21⁷)

A 200k-sample fuzz over long, ulong, Int128, UInt128, byte and BigInteger found no other failures. Cbrt (degree 3) passed throughout.

CLAUDE.md says Cbrt and RootN "refine every integer type in integer arithmetic, so their floor is exact". So any quantity code that takes an integer root of a perfect power in short or int storage gets a result one unit too small.

Cause

RootByDescent (Semantics.Quantities/StorageMath.cs, ~L803-840) relies on the invariant that the estimate stays at or above the root. The overflow branch breaks it:

if (!TryPower(estimate, degree - 1, out T power) || T.IsZero(power))
{
    // ... Halving reaches a range the type holds, and stays at or above the root.
    estimate = (estimate + T.One) / two;
    continue;
}

Traced for (short)15625, degree 6:

  1. The seed is 4, and 4⁶ = 4096 is below 15625, so the lift doubles it to 8. 8⁶ overflows short, so the lift stops.
  2. 8⁵ = 32768 overflows short, so the branch halves the estimate: (8+1)/2 = 4. That is below the root of 5.
  3. The Newton step from 4 gives next = (5·4 + 15625/4⁵)/6 = (20 + 15)/6 = 5. Since next >= estimate, the loop returns the stale 4.

Halving is only safe while the halved value is still ≥ the root. Once the lift has doubled past the root, the value before doubling may have been the only thing known to be below it, and halving can drop back to that.

Suggested fix

Either of these:

Acceptance criteria

  • The five cases above return 5, 4, 19, 20 and 21.
  • A test checks RootN for sbyte, short, int (and their unsigned counterparts) against a BigInteger floor-root at every exact power kᵈ the type holds, for degrees 4–10, and at kᵈ − 1.

Activity

  1. added
    bug
    on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions