Skip to content
Standard library

BigInt#

import { BigInt, BigIntError } from "velt/math". Arbitrary-precision integers, like JavaScript's BigInt, backed by the runtime. Velt has no operator overloading and no 10n literals, so arithmetic is methods: a.add(b) is JavaScript's a + b, and a.addAssign(b) is a += b.

ts
import { BigInt } from "velt/math";

function factorial(n: i64): BigInt {
  const acc = new BigInt(1);
  for (let i = 2; i <= n; i++) {
    acc.mulIntAssign(i);
  }
  return acc;
}

const f = factorial(25);
console.log(f.toString()); // 15511210043330985984000000
const big = BigInt.parse("ffffffffffffffff", 16);
console.log(big.addInt(1).toString(16), f.compareTo(big) > 0); // 10000000000000000 true

Making one#

  • new BigInt(value: i64 = 0).
  • BigInt.fromNumber(x: f64): the integer part of x; panics on NaN and ±Infinity.
  • BigInt.parse(s, radix = 10): an optional sign, then digits. Throws BigIntError for anything else (JavaScript throws a SyntaxError).

Arithmetic#

  • Returning a new value, like a + b: add sub mul div rem (with a BigInt), addInt subInt mulInt divInt remInt (with an i64, without building a BigInt for it), shl(n), shr(n), neg().
  • In place, like a += b, reusing the number's buffer: addAssign subAssign mulAssign divAssign remAssign, addIntAssign subIntAssign mulIntAssign divIntAssign, shlAssign, shrAssign, and set(other). Use these in hot loops: they allocate only when the number grows.

Division truncates toward zero and rem takes the dividend's sign, as in JavaScript. Dividing by zero panics with a RangeError, where JavaScript throws one, and so does a negative shift count.

Comparing and converting#

  • compareTo(other): i64, compareToInt(k), equals(other). BigInt does not declare implements Comparable, so < and > don't apply to it: write a.compareTo(b) < 0.
  • toString(radix = 10) (2 to 36, lowercase), toNumber(): f64, toI64() (the low 64 bits, as JavaScript's BigInt.asIntN(64, big)).
  • clone() copies the number. Assigning a BigInt to another variable shares it, as with any object, so a later addAssign shows through both; clone first when you need two.

A BigInt owns a runtime handle that is freed when the value is dropped.

Edit this page on GitHub