std.bigint - D Programming Language (original) (raw)
Arbitrary-precision ('bignum') arithmetic.
Performance is optimized for numbers below ~1000 decimal digits. For X86 machines, highly optimised assembly routines are used.
The following algorithms are currently implemented:
- Karatsuba multiplication
- Squaring is optimized independently of multiplication
- Divide-and-conquer division
- Binary exponentiation
For very large numbers, consider using the GMP library instead.
A struct representing an arbitrary precision integer.
All arithmetic operations are supported, except unsigned shift right (>>>). Bitwise operations (|, &, ^, ~) are supported, and behave as if BigInt was an infinite length 2's complement number.
BigInt implements value semantics using copy-on-write. This means that assignment is cheap, but operations such as x++ will cause heap allocation. (But note that for most bigint operations, heap allocation is inevitable anyway.)
Examples:
BigInt a = "9588669891916142"; BigInt b = "7452469135154800"; auto c = a * b; writeln(c); auto d = b * a; writeln(d); writeln(d); d = c * BigInt("794628672112"); writeln(d); auto e = c + d; writeln(e); auto f = d + c; writeln(f); auto g = f - c; writeln(g); g = f - d; writeln(g); e = 12345678; g = c + e; auto h = g / b; auto i = g % b; writeln(h); writeln(i); BigInt j = "-0x9A56_57f4_7B83_AB78"; BigInt k = j; j ^^= 11; writeln(k^^11);
this(Range)(Range s)
if (isBidirectionalRange!Range && isSomeChar!(ElementType!Range) && !isInfinite!Range && !isNarrowString!Range);
pure this(Range)(Range s)
if (isNarrowString!Range);
Construct a BigInt from a decimal or hexadecimal string. The number must be in the form of a decimal or hex literal. It may have a leading + or - sign, followed by 0x or 0X if hexadecimal. Underscores are permitted in any location after the 0x and/or the sign of the number.
Parameters:
| Range s | a finite bidirectional range of any character type |
|---|
this(Range)(bool isNegative, Range magnitude)
if (isInputRange!Range && isUnsigned!(ElementType!Range) && (hasLength!Range || isForwardRange!Range) && !isInfinite!Range);
Construct a BigInt from a sign and a magnitude.
Parameters:
| bool isNegative | true for negative, false for non-negative (ignored when magnitude is zero) |
|---|---|
| Range magnitude | a finite range of unsigned integers |
Examples:
ubyte[] magnitude = [1, 2, 3, 4, 5, 6]; auto b1 = BigInt(false, magnitude); writeln(cast(long)b1); auto b2 = BigInt(true, magnitude); writeln(cast(long)b2);
pure nothrow @safe this(T)(T x)
if (isIntegral!T);
Construct a BigInt from a built-in integral type.
Examples:
ulong data = 1_000_000_000_000; auto bigData = BigInt(data); writeln(bigData);
pure nothrow @safe this(T)(T x)
if (is(immutable(T) == immutable(BigInt)));
Construct a BigInt from another BigInt.
Examples:
const(BigInt) b1 = BigInt("1_234_567_890"); BigInt b2 = BigInt(b1); writeln(b2);
pure nothrow @safe BigInt opAssign(T)(T x)
if (isIntegral!T);
Assignment from built-in integer types.
Examples:
auto b = BigInt("123"); b = 456; writeln(b);
pure @nogc @safe BigInt opAssign(T : BigInt)(T x);
Assignment from another BigInt.
Examples:
auto b1 = BigInt("123"); auto b2 = BigInt("456"); b2 = b1; writeln(b2);
pure nothrow @safe BigInt opOpAssign(string op, T)(T y) return scope
if ((op == "+" || op == "-" || op == "*" || op == "/" || op == "%" || op == ">>" || op == "<<" || op == "^^" || op == "|" || op == "&" || op == "^") && isIntegral!T);
Implements assignment operators from built-in integers of the formBigInt op= integer.
Examples:
auto b = BigInt("1_000_000_000");
b += 12345; writeln(b); b /= 5; writeln(b);
pure nothrow @safe BigInt opOpAssign(string op, T)(T y) return scope
if ((op == "+" || op == "-" || op == "*" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt));
Implements assignment operators of the form BigInt op= BigInt.
Examples:
auto x = BigInt("123"); auto y = BigInt("321"); x += y; writeln(x);
pure nothrow @safe BigInt opBinary(string op, T)(T y) const return scope
if ((op == "+" || op == "*" || op == "-" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt));
Implements binary operators between BigInts.
Examples:
auto x = BigInt("123"); auto y = BigInt("456"); BigInt z = x * y; writeln(z);
pure nothrow @safe BigInt opBinary(string op, T)(T y) const return scope
if ((op == "+" || op == "*" || op == "-" || op == "/" || op == "|" || op == "&" || op == "^" || op == ">>" || op == "<<" || op == "^^") && isIntegral!T);
Implements binary operators between BigInt's and built-in integers.
Examples:
auto x = BigInt("123"); x *= 300; writeln(x);
pure nothrow @safe auto opBinary(string op, T)(T y) const
if (op == "%" && isIntegral!T);
Implements a narrowing remainder operation with built-in integer types.
This binary operator returns a narrower, built-in integer type where applicable, according to the following table.
| BigInt | % | uint | → | long |
|---|---|---|---|---|
| BigInt | % | long | → | long |
| BigInt | % | ulong | → | BigInt |
| BigInt | % | other type | → | int |
Examples:
auto x = BigInt("1_000_000_500"); long l = 1_000_000L; ulong ul = 2_000_000UL; int i = 500_000; short s = 30_000;
assert(is(typeof(x % l) == long) && x % l == 500L); assert(is(typeof(x % ul) == BigInt) && x % ul == BigInt(500)); assert(is(typeof(x % i) == int) && x % i == 500); assert(is(typeof(x % s) == int) && x % s == 10500);
pure nothrow @safe BigInt opBinaryRight(string op, T)(T y) const
if ((op == "+" || op == "*" || op == "|" || op == "&" || op == "^") && isIntegral!T);
pure nothrow @safe BigInt opBinaryRight(string op, T)(T y) const
if (op == "-" && isIntegral!T);
pure nothrow @safe T opBinaryRight(string op, T)(T x) const
if ((op == "%" || op == "/") && isIntegral!T);
Implements operators with built-in integers on the left-hand side andBigInt on the right-hand side.
Examples:
auto x = BigInt("100"); BigInt y = 123 + x; writeln(y); BigInt z = 123 - x; writeln(z); assert(is(typeof(1000 / x) == int)); writeln(1000 / x);
pure nothrow @safe BigInt opUnary(string op)() const
if (op == "+" || op == "-" || op == "~");
pure nothrow @safe BigInt opUnary(string op)()
if (op == "++" || op == "--");
Implements BigInt unary operators.
Examples:
auto x = BigInt("1234"); writeln(-x); ++x; writeln(x);
pure @nogc @safe bool opEquals()(auto ref const BigInt y) const;
pure nothrow @nogc @safe bool opEquals(T)(const T y) const
if (isIntegral!T);
pure nothrow @nogc bool opEquals(T)(const T y) const
if (isFloatingPoint!T);
Implements BigInt equality test with other BigInt's and built-in numeric types.
Examples:
assert(BigInt(123456789) != cast(float) 123456789);
pure nothrow @nogc @safe T opCast(T : bool)() const;
Implements casting to bool.
Examples:
auto x = BigInt("1"); auto y = BigInt("10"); assert(x); assert(y);
auto z = BigInt("0"); assert(!z);
pure @safe T opCast(T : ulong)() const;
Implements casting to integer types.
Examples:
import std.conv : to, ConvOverflowException; import std.exception : assertThrown;
writeln(BigInt("0").to!int); writeln(BigInt("0").to!ubyte); writeln(BigInt("255").to!ubyte); assertThrown!ConvOverflowException(BigInt("256").to!ubyte); assertThrown!ConvOverflowException(BigInt("-1").to!ubyte);
nothrow @nogc @safe T opCast(T)() const
if (isFloatingPoint!T);
Implements casting to floating point types.
Examples:
assert(cast(float) BigInt("35540592535949172786332045140593475584") == 35540592535949172786332045140593475584.0f); assert(cast(double) BigInt("35540601499647381470685035515422441472") == 35540601499647381470685035515422441472.0); assert(cast(real) BigInt("35540601499647381470685035515422441472") == 35540601499647381470685035515422441472.0L);
writeln(cast(float)BigInt("-0x1345_6780_0000_0000_0000_0000_0000")); writeln(cast(double)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000")); writeln(cast(real)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000"));
Examples:
Rounding when casting to floating point
writeln(cast(float)BigInt(0x1aaa_aae7)); writeln(cast(float)BigInt(0x1aaa_aaff)); writeln(cast(float)BigInt(-0x1aaa_aae7)); writeln(cast(float)BigInt(-0x1aaa_aaff)); writeln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aa77)); writeln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aaff)); writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa77)); writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aaff)); writeln(cast(float)BigInt(0x1aaa_aaf0)); writeln(cast(float)BigInt(-0x1aaa_aaf0)); writeln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aa80)); writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa80)); writeln(cast(float)BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999")); writeln(cast(float)BigInt("-999_999_999_999_999_999_999_999_999_999_999_999_999"));
assert(cast(double) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") < double.infinity); assert(cast(real) BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999") < real.infinity);
pure nothrow @nogc T opCast(T)() const
if (is(immutable(T) == immutable(BigInt)));
Implements casting to/from qualified BigInt's.
WarningCasting to/from const or immutable may break type system guarantees. Use with care.
Examples:
const(BigInt) x = BigInt("123"); BigInt y = cast() x; writeln(y);
pure nothrow @nogc @safe int opCmp(ref const BigInt y) const;
pure nothrow @nogc @safe int opCmp(T)(const T y) const
if (isIntegral!T);
nothrow @nogc @safe int opCmp(T)(const T y) const
if (isFloatingPoint!T);
pure nothrow @nogc @safe int opCmp(T : BigInt)(const T y) const;
Implements 3-way comparisons of BigInt with BigInt or BigInt with built-in numeric types.
Examples:
auto x = BigInt("100"); auto y = BigInt("10"); int z = 50; const int w = 200;
assert(y < x); assert(x > z); assert(z > y); assert(x < w);
Examples:
auto x = BigInt("0x1abc_de80_0000_0000_0000_0000_0000_0000"); BigInt y = x - 1; BigInt z = x + 1;
double d = 0x1.abcde8p124; assert(y < d); assert(z > d); assert(x >= d && x <= d);
assert(BigInt(123456789) < cast(float) 123456789);
pure nothrow @nogc @safe long toLong() const;
Returns:
The value of this BigInt as a long, or long.max/long.min if outside the representable range.
Examples:
auto b = BigInt("12345"); long l = b.toLong(); writeln(l);
pure nothrow @nogc @safe int toInt() const;
Returns:
The value of this BigInt as an int, or int.max/int.min if outside the representable range.
Examples:
auto big = BigInt("5_000_000"); auto i = big.toInt(); writeln(i); auto tooBig = BigInt("5_000_000_000"); i = tooBig.toInt(); writeln(i);
pure nothrow @nogc @property @safe size_t uintLength() const;
Number of significant uints which are used in storing this number. The absolute value of this BigInt is always < 232*uintLength
pure nothrow @nogc @property @safe size_t ulongLength() const;
Number of significant ulongs which are used in storing this number. The absolute value of this BigInt is always < 264*ulongLength
void toString(Writer)(ref scope Writer sink, string formatString) const;
void toString(Writer)(ref scope Writer sink, ref scope const FormatSpec!char f) const;
void toString(scope void delegate(scope const(char)[]) sink, string formatString) const;
void toString(scope void delegate(scope const(char)[]) sink, ref scope const FormatSpec!char f) const;
Convert the BigInt to string, passing it to the given sink.
Parameters:
| Writer sink | An OutputRange for accepting possibly piecewise segments of the formatted string. |
|---|---|
| string formatString | A format string specifying the output format. Available output formats: "d" Decimal "o" Octal "x" Hexadecimal, lower case "X" Hexadecimal, upper case "s" Default formatting (same as "d") null Default formatting (same as "d") |
Examples:
toString is rarely directly invoked; the usual way of using it is viastd.format.format:
import std.format : format;
auto x = BigInt("1_000_000"); x *= 12345;
writeln(format("%d", x)); writeln(format("%x", x)); writeln(format("%X", x)); writeln(format("%o", x));
pure nothrow @nogc @safe size_t toHash() const;
Returns:
A unique hash of the BigInt's value suitable for use in a hash table.
Examples:
toHash is rarely directly invoked; it is implicitly used when BigInt is used as the key of an associative array.
string[BigInt] aa; aa[BigInt(123)] = "abc"; aa[BigInt(456)] = "def";
writeln(aa[BigInt(123)]); writeln(aa[BigInt(456)]);
T getDigit(T = ulong)(size_t n) const
if (is(T == ulong) || is(T == uint));
Gets the nth number in the underlying representation that makes up the wholeBigInt.
Parameters:
| T | the type to view the underlying representation as |
|---|---|
| size_t n | The nth number to retrieve. Must be less than ulongLength oruintLength with respect to T. |
Returns:
The nth ulong in the representation of this BigInt.
Examples:
auto a = BigInt("1000"); writeln(a.ulongLength()); writeln(a.getDigit(0)); writeln(a.uintLength()); writeln(a.getDigit!uint(0)); auto b = BigInt("2_000_000_000_000_000_000_000_000_000"); writeln(b.ulongLength()); writeln(b.getDigit(0)); writeln(b.getDigit(1)); writeln(b.uintLength()); writeln(b.getDigit!uint(0)); writeln(b.getDigit!uint(1)); writeln(b.getDigit!uint(2));
pure nothrow @safe string toDecimalString(const(BigInt) x);
Parameters:
| const(BigInt) x | The BigInt to convert to a decimal string. |
|---|
Returns:
A string that represents the BigInt as a decimal number.
Examples:
auto x = BigInt("123"); x *= 1000; x += 456;
auto xstr = x.toDecimalString(); writeln(xstr);
pure @safe string toHex(const(BigInt) x);
Parameters:
| const(BigInt) x | The BigInt to convert to a hexadecimal string. |
|---|
Returns:
A string that represents the BigInt as a hexadecimal (base 16) number in upper case.
Examples:
auto x = BigInt("123"); x *= 1000; x += 456;
auto xstr = x.toHex(); writeln(xstr);
Unsigned!T absUnsign(T)(T x)
if (isIntegral!T);
Returns the absolute value of x converted to the corresponding unsigned type.
Parameters:
| T x | The integral value to return the absolute value of. |
|---|
Returns:
The absolute value of x.
Examples:
writeln((-1).absUnsign); writeln(1.absUnsign);
pure nothrow @safe void divMod(const BigInt dividend, const BigInt divisor, out BigInt quotient, out BigInt remainder);
Finds the quotient and remainder for the given dividend and divisor in one operation.
Parameters:
| BigInt dividend | the BigInt to divide |
|---|---|
| BigInt divisor | the BigInt to divide the dividend by |
| BigInt quotient | is set to the result of the division |
| BigInt remainder | is set to the remainder of the division |
Examples:
auto a = BigInt(123); auto b = BigInt(25); BigInt q, r;
divMod(a, b, q, r);
writeln(q); writeln(r); writeln(q * b + r);
pure nothrow @safe BigInt powmod(BigInt base, BigInt exponent, BigInt modulus);
Fast power modulus calculation for BigInt operands.
Parameters:
| BigInt base | the BigInt is basic operands. |
|---|---|
| BigInt exponent | the BigInt is power exponent of base. |
| BigInt modulus | the BigInt is modules to be modular of base ^ exponent. |
Returns:
The power modulus value of (base ^ exponent) % modulus.
Examples:
for powmod
BigInt base = BigInt("123456789012345678901234567890"); BigInt exponent = BigInt("1234567890123456789012345678901234567"); BigInt modulus = BigInt("1234567");
BigInt result = powmod(base, exponent, modulus); writeln(result);
Copyright © 1999-2026 by the D Language Foundation | Page generated byDdoc on Thu Apr 9 23:12:44 2026