vitest-dev/vitest · error · Error

Negative numbers are not supported

Error message

Negative numbers are not supported

What it means

Thrown by the internal bigIntSquareRoot() helper in examples/profiling when its argument is a negative BigInt. The Newton's-method square root iteration is only defined for non-negative values, so the guard fails fast. Note: bigIntSquareRoot is not exported and is unreachable through getPrimeNumbers (which only produces positive BigInts), so this fires only if the helper is reused directly with a negative input.

Source

Thrown at examples/profiling/src/prime-number.ts:62

  if (number === 3n) {
    return true
  }

  const squareRoot = bigIntSquareRoot(number)

  // Intentionally inefficient to highlight performance issues
  for (let i = 3n; i < squareRoot; i += 2n) {
    if (number % i === 0n) {
      return false
    }
  }

  return true
}

function bigIntSquareRoot(number: bigint): bigint {
  if (number < 0n) {
    throw new Error('Negative numbers are not supported')
  }
  if (number < 2n) {
    return number
  }

  function iterate(value: bigint, guess: bigint): bigint {
    const nextGuess = (value / guess + guess) >> 1n

    if (guess === nextGuess) {
      return guess
    }
    if (guess === nextGuess - 1n) {
      return guess
    }

    return iterate(value, nextGuess)
  }

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Pass only non-negative BigInts to the square-root helper.
  2. If you may receive signed values, clamp or take the absolute value first: bigIntSquareRoot(value < 0n ? -value : value).
  3. Add an upstream guard so callers cannot reach this path with negative data.

Example fix

// before
bigIntSquareRoot(a - b) // a < b -> negative -> throws

// after
const diff = a < b ? b - a : a - b
bigIntSquareRoot(diff)
Defensive patterns

Strategy: validation

Validate before calling

function safeSqrt(n: bigint): bigint {
  if (n < 0n) throw new RangeError(`expected non-negative bigint, got ${n}`)
  return bigIntSquareRoot(n)
}

Type guard

function isNonNegativeBigInt(v: unknown): v is bigint {
  return typeof v === 'bigint' && v >= 0n
}

Prevention

When it happens

Trigger: Calling bigIntSquareRoot(-1n) or any negative BigInt. Through the public getPrimeNumbers path this is effectively unreachable because randomBigInt always yields positive values.

Common situations: Copying the helper into another project and feeding it a signed difference (e.g. a - b where a < b), or unit-testing the internal helper directly with negative fixtures.

Related errors


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/e7ccd369eb2e665c.json. Report an issue: GitHub.