Hyperlinkv0.8.0-beta.28

BigInt

BigInt.sqrtUnsafeconsteffect/BigInt.ts:699
(n: bigint): bigint

Returns the integer square root of a non-negative bigint.

When to use

Use when you need to compute an integer square root for a bigint that has already been validated as non-negative, and you want negative input to throw instead of returning Option.none.

Details

For non-perfect squares, returns the largest bigint whose square is less than or equal to the input.

Gotchas

Throws a RangeError if the input is negative.

Example (Calculating square roots unsafely)

import { BigInt } from "effect"
import * as assert from "node:assert"

assert.deepStrictEqual(BigInt.sqrtUnsafe(4n), 2n)
assert.deepStrictEqual(BigInt.sqrtUnsafe(9n), 3n)
assert.deepStrictEqual(BigInt.sqrtUnsafe(16n), 4n)
mathsqrt
Source effect/BigInt.ts:69913 lines
export const sqrtUnsafe = (n: bigint): bigint => {
  if (n < bigint0) {
    throw new RangeError("Cannot take the square root of a negative number")
  }
  if (n < bigint2) {
    return n
  }
  let x = n / bigint2
  while (x * x > n) {
    x = ((n / x) + x) / bigint2
  }
  return x
}
Referenced by 1 symbols