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 trueMaking one
new BigInt(value: i64 = 0).BigInt.fromNumber(x: f64): the integer part ofx; panics onNaNand ±Infinity.BigInt.parse(s, radix = 10): an optional sign, then digits. ThrowsBigIntErrorfor anything else (JavaScript throws aSyntaxError).
Arithmetic
- Returning a new value, like
a + b:add sub mul div rem(with aBigInt),addInt subInt mulInt divInt remInt(with ani64, without building aBigIntfor 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, andset(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).BigIntdoes not declareimplements Comparable, so<and>don't apply to it: writea.compareTo(b) < 0.toString(radix = 10)(2 to 36, lowercase),toNumber(): f64,toI64()(the low 64 bits, as JavaScript'sBigInt.asIntN(64, big)).clone()copies the number. Assigning aBigIntto another variable shares it, as with any object, so a lateraddAssignshows through both; clone first when you need two.
A BigInt owns a runtime handle that is freed when the value is dropped.