Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.bigint

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 theGMP library instead.
License:
Boost License 1.0.
Authors:
Don Clugston

Sourcestd/bigint.d

structBigInt;
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);// BigInt("71459266416693160362545788781600")auto d = b * a;writeln(d);// BigInt("71459266416693160362545788781600")writeln(d);// cd = c *BigInt("794628672112");writeln(d);// BigInt("56783581982794522489042432639320434378739200")auto e = c + d;writeln(e);// BigInt("56783581982865981755459125799682980167520800")auto f = d + c;writeln(f);// eauto g = f - c;writeln(g);// dg = f - d;writeln(g);// ce = 12345678;g = c + e;auto h = g / b;auto i = g % b;writeln(h);// awriteln(i);// eBigInt j ="-0x9A56_57f4_7B83_AB78";BigInt k = j;j ^^= 11;writeln(k^^11);// j
this(Range)(Ranges)
if (isBidirectionalRange!Range && isSomeChar!(ElementType!Range) && !isInfinite!Range && !isNarrowString!Range);

pure this(Range)(Ranges)
if (isNarrowString!Range);
Construct aBigInt 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 by0x or0X if hexadecimal. Underscores are permitted in any location after the0x and/or the sign of the number.
Parameters:
Rangesa finite bidirectional range of any character type
Throws:
std.conv.ConvException if the string doesn't represent a valid number
this(Range)(boolisNegative, Rangemagnitude)
if (isInputRange!Range && isUnsigned!(ElementType!Range) && (hasLength!Range || isForwardRange!Range) && !isInfinite!Range);
Construct aBigInt from a sign and a magnitude.
The magnitude is aninput range of unsigned integers that satisfies eitherstd.range.primitives.hasLength orstd.range.primitives.isForwardRange. The first (leftmost) element of the magnitude is considered the most significant.
Parameters:
boolisNegativetrue for negative, false for non-negative (ignored when magnitude is zero)
Rangemagnitudea finite range of unsigned integers
Examples:
ubyte[]magnitude = [1, 2, 3, 4, 5, 6];auto b1 = BigInt(false,magnitude);writeln(cast(long)b1);// 0x01_02_03_04_05_06Lauto b2 = BigInt(true,magnitude);writeln(cast(long)b2);// -0x01_02_03_04_05_06L
pure nothrow @safe this(T)(Tx)
if (isIntegral!T);
Construct aBigInt from a built-in integral type.
Examples:
ulong data = 1_000_000_000_000;auto bigData = BigInt(data);writeln(bigData);// BigInt("1_000_000_000_000")
pure nothrow @safe this(T)(Tx)
if (is(immutable(T) == immutable(BigInt)));
Construct aBigInt from anotherBigInt.
Examples:
const(BigInt) b1 = BigInt("1_234_567_890");BigInt b2 = BigInt(b1);writeln(b2);// BigInt("1_234_567_890")
pure nothrow @safe BigIntopAssign(T)(Tx)
if (isIntegral!T);
Assignment from built-in integer types.
Examples:
auto b = BigInt("123");b = 456;writeln(b);// BigInt("456")
pure @nogc @safe BigIntopAssign(T : BigInt)(Tx);
Assignment from another BigInt.
Examples:
auto b1 = BigInt("123");auto b2 = BigInt("456");b2 = b1;writeln(b2);// BigInt("123")
pure nothrow @safe BigIntopOpAssign(string op, T)(Ty) 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);// BigInt("1_000_012_345")b /= 5;writeln(b);// BigInt("200_002_469")
pure nothrow @safe BigIntopOpAssign(string op, T)(Ty) return scope
if ((op == "+" || op == "-" || op == "*" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt));
Implements assignment operators of the formBigInt op= BigInt.
Examples:
auto x = BigInt("123");autoy = BigInt("321");x +=y;writeln(x);// BigInt("444")
pure nothrow @safe BigIntopBinary(string op, T)(Ty) const return scope
if ((op == "+" || op == "*" || op == "-" || op == "|" || op == "&" || op == "^" || op == "/" || op == "%") && is(T : BigInt));
Implements binary operators betweenBigInts.
Examples:
auto x = BigInt("123");autoy = BigInt("456");BigInt z = x *y;writeln(z);// BigInt("56088")
pure nothrow @safe BigIntopBinary(string op, T)(Ty) const return scope
if ((op == "+" || op == "*" || op == "-" || op == "/" || op == "|" || op == "&" || op == "^" || op == ">>" || op == "<<" || op == "^^") && isIntegral!T);
Implements binary operators betweenBigInt's and built-in integers.
Examples:
auto x = BigInt("123");x *= 300;writeln(x);// BigInt("36900")
pure nothrow @safe autoopBinary(string op, T)(Ty) 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%uintlong
BigInt%longlong
BigInt%ulongBigInt
BigInt%other typeint
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 BigIntopBinaryRight(string op, T)(Ty) const
if ((op == "+" || op == "*" || op == "|" || op == "&" || op == "^") && isIntegral!T);

pure nothrow @safe BigIntopBinaryRight(string op, T)(Ty) const
if (op == "-" && isIntegral!T);

pure nothrow @safe TopBinaryRight(string op, T)(Tx) const
if ((op == "%" || op == "/") && isIntegral!T);
Implements operators with built-in integers on the left-hand side andBigInt on the right-hand side.
Examples:
autox = BigInt("100");BigInty = 123 +x;writeln(y);// BigInt("223")BigInt z = 123 -x;writeln(z);// BigInt("23")// Dividing a built-in integer type by BigInt always results in// something that fits in a built-in type, so the built-in type is// returned, not BigInt.assert(is(typeof(1000 /x) ==int));writeln(1000 /x);// 10
pure nothrow @safe BigIntopUnary(string op)() const
if (op == "+" || op == "-" || op == "~");

pure nothrow @safe BigIntopUnary(string op)()
if (op == "++" || op == "--");
ImplementsBigInt unary operators.
Examples:
auto x = BigInt("1234");writeln(-x);// BigInt("-1234")++x;writeln(x);// BigInt("1235")
pure @nogc @safe boolopEquals()(auto ref const BigInty) const;

pure nothrow @nogc @safe boolopEquals(T)(const Ty) const
if (isIntegral!T);

pure nothrow @nogc boolopEquals(T)(const Ty) const
if (isFloatingPoint!T);
ImplementsBigInt equality test with otherBigInt's and built-in numeric types.
Examples:
// Note that when comparing a BigInt to a float or double the// full precision of the BigInt is always considered, unlike// when comparing an int to a float or a long to a double.assert(BigInt(123456789) !=cast(float) 123456789);
pure nothrow @nogc @safe TopCast(T : bool)() const;
Implements casting tobool.
Examples:
// Non-zero values are regarded as trueauto x = BigInt("1");auto y = BigInt("10");assert(x);assert(y);// Zero value is regarded as falseauto z = BigInt("0");assert(!z);
pure @safe TopCast(T : ulong)() const;
Implements casting to integer types.
Throws:
std.conv.ConvOverflowException if the number exceeds the target type's range.
Examples:
import std.conv : to, ConvOverflowException;import std.exception : assertThrown;writeln(BigInt("0").to!int);// 0writeln(BigInt("0").to!ubyte);// 0writeln(BigInt("255").to!ubyte);// 255assertThrown!ConvOverflowException(BigInt("256").to!ubyte);assertThrown!ConvOverflowException(BigInt("-1").to!ubyte);
nothrow @nogc @safe TopCast(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"));// -0x1.3456_78p+108f// -0x1.3456_78ab_cdefp+108writeln(cast(double)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000"));// -0x1.3456_78ab_cdefp+108Lwriteln(cast(real)BigInt("-0x1345_678a_bcde_f000_0000_0000_0000"));
Examples:
Rounding when casting to floating point
// BigInts whose values cannot be exactly represented as float/double/real// are rounded when cast to float/double/real. When cast to float or// double or 64-bit real the rounding is strictly defined. When cast// to extended-precision real the rounding rules vary by environment.// BigInts that fall somewhere between two non-infinite floats/doubles// are rounded to the closer value when cast to float/double.writeln(cast(float)BigInt(0x1aaa_aae7));// 0x1.aaa_aaep+28fwriteln(cast(float)BigInt(0x1aaa_aaff));// 0x1.aaa_ab0p+28fwriteln(cast(float)BigInt(-0x1aaa_aae7));// -0x1.aaaaaep+28fwriteln(cast(float)BigInt(-0x1aaa_aaff));// -0x1.aaaab0p+28fwriteln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aa77));// 0x1.aaa_aaaa_aaaa_aa00p+60writeln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aaff));// 0x1.aaa_aaaa_aaaa_ab00p+60writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa77));// -0x1.aaa_aaaa_aaaa_aa00p+60writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aaff));// -0x1.aaa_aaaa_aaaa_ab00p+60// BigInts that fall exactly between two non-infinite floats/doubles// are rounded away from zero when cast to float/double. (Note that// in most environments this is NOT the same rounding rule rule used// when casting int/long to float/double.)writeln(cast(float)BigInt(0x1aaa_aaf0));// 0x1.aaa_ab0p+28fwriteln(cast(float)BigInt(-0x1aaa_aaf0));// -0x1.aaaab0p+28fwriteln(cast(double)BigInt(0x1aaa_aaaa_aaaa_aa80));// 0x1.aaa_aaaa_aaaa_ab00p+60writeln(cast(double)BigInt(-0x1aaa_aaaa_aaaa_aa80));// -0x1.aaa_aaaa_aaaa_ab00p+60// BigInts that are bounded on one side by the largest positive or// most negative finite float/double and on the other side by infinity// or -infinity are rounded as if in place of infinity was the value// `2^^(T.max_exp)` when cast to float/double.// float.infinitywriteln(cast(float)BigInt("999_999_999_999_999_999_999_999_999_999_999_999_999"));// -float.infinitywriteln(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 TopCast(T)() const
if (is(immutable(T) == immutable(BigInt)));
Implements casting to/from qualifiedBigInt's.

WarningCasting to/fromconst orimmutable may break type system guarantees. Use with care.

Examples:
const(BigInt) x = BigInt("123");BigInt y =cast() x;// cast away constwriteln(y);// x
pure nothrow @nogc @safe intopCmp(ref const BigInty) const;

pure nothrow @nogc @safe intopCmp(T)(const Ty) const
if (isIntegral!T);

nothrow @nogc @safe intopCmp(T)(const Ty) const
if (isFloatingPoint!T);

pure nothrow @nogc @safe intopCmp(T : BigInt)(const Ty) const;
Implements 3-way comparisons ofBigInt withBigInt orBigInt with built-in numeric types.
Examples:
auto x = BigInt("100");autoy = BigInt("10");int z = 50;constint 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");BigInty = x - 1;BigInt z = x + 1;double d = 0x1.abcde8p124;assert(y < d);assert(z > d);assert(x >= d && x <= d);// Note that when comparing a BigInt to a float or double the// full precision of the BigInt is always considered, unlike// when comparing an int to a float or a long to a double.assert(BigInt(123456789) <cast(float) 123456789);
pure nothrow @nogc @safe longtoLong() const;
Returns:
The value of thisBigInt as along, orlong.max/long.min if outside the representable range.
Examples:
auto b = BigInt("12345");long l = b.toLong();writeln(l);// 12345
pure nothrow @nogc @safe inttoInt() const;
Returns:
The value of thisBigInt as anint, orint.max/int.min if outside the representable range.
Examples:
auto big = BigInt("5_000_000");auto i = big.toInt();writeln(i);// 5_000_000// Numbers that are too big to fit into an int will be clamped to int.max.auto tooBig = BigInt("5_000_000_000");i = tooBig.toInt();writeln(i);// int.max
pure nothrow @nogc @property @safe size_tuintLength() const;
Number of significantuints which are used in storing this number.The absolute value of thisBigInt is always < 232*uintLength
pure nothrow @nogc @property @safe size_tulongLength() const;
Number of significantulongs which are used in storing this number.The absolute value of thisBigInt is always < 264*ulongLength
voidtoString(Writer)(ref scope Writersink, stringformatString) const;

voidtoString(Writer)(ref scope Writersink, ref scope const FormatSpec!charf) const;

voidtoString(scope void delegate(scope const(char)[])sink, stringformatString) const;

voidtoString(scope void delegate(scope const(char)[])sink, ref scope const FormatSpec!charf) const;
Convert theBigInt tostring, passing it to the given sink.
Parameters:
WritersinkAn OutputRange for accepting possibly piecewise segments of the formatted string.
stringformatStringA 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")
nullDefault 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));// "12345000000"writeln(format("%x", x));// "2_dfd1c040"writeln(format("%X", x));// "2_DFD1C040"writeln(format("%o", x));// "133764340100"
pure nothrow @nogc @safe size_ttoHash() const;
Returns:
A unique hash of theBigInt'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)]);// "abc"writeln(aa[BigInt(456)]);// "def"
TgetDigit(T = ulong)(size_tn) const
if (is(T == ulong) || is(T == uint));
Gets the nth number in the underlying representation that makes up the wholeBigInt.
Parameters:
Tthe type to view the underlying representation as
size_tnThe nth number to retrieve. Must be less thanulongLength oruintLength with respect toT.
Returns:
The nthulong in the representation of thisBigInt.
Examples:
auto a = BigInt("1000");writeln(a.ulongLength());// 1writeln(a.getDigit(0));// 1000writeln(a.uintLength());// 1writeln(a.getDigit!uint(0));// 1000auto b = BigInt("2_000_000_000_000_000_000_000_000_000");writeln(b.ulongLength());// 2writeln(b.getDigit(0));// 4584946418820579328writeln(b.getDigit(1));// 108420217writeln(b.uintLength());// 3writeln(b.getDigit!uint(0));// 3489660928writeln(b.getDigit!uint(1));// 1067516025writeln(b.getDigit!uint(2));// 108420217
pure nothrow @safe stringtoDecimalString(const(BigInt)x);
Parameters:
const(BigInt)xTheBigInt to convert to a decimalstring.
Returns:
Astring that represents theBigInt as a decimal number.
Examples:
autox = BigInt("123");x *= 1000;x += 456;auto xstr =x.toDecimalString();writeln(xstr);// "123456"
pure @safe stringtoHex(const(BigInt)x);
Parameters:
const(BigInt)xTheBigInt to convert to a hexadecimalstring.
Returns:
Astring that represents theBigInt as a hexadecimal (base 16) number in upper case.
Examples:
autox = BigInt("123");x *= 1000;x += 456;auto xstr =x.toHex();writeln(xstr);// "1E240"
Unsigned!TabsUnsign(T)(Tx)
if (isIntegral!T);
Returns the absolute value of x converted to the corresponding unsignedtype.
Parameters:
TxThe integral value to return the absolute value of.
Returns:
The absolute value of x.
Examples:
writeln((-1).absUnsign);// 1writeln(1.absUnsign);// 1
pure nothrow @safe voiddivMod(const BigIntdividend, const BigIntdivisor, out BigIntquotient, out BigIntremainder);
Finds the quotient and remainder for the given dividend and divisor in one operation.
Parameters:
BigIntdividendtheBigInt to divide
BigIntdivisortheBigInt to divide the dividend by
BigIntquotientis set to the result of the division
BigIntremainderis 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);// 4writeln(r);// 23writeln(q * b + r);// a
pure nothrow @safe BigIntpowmod(BigIntbase, BigIntexponent, BigIntmodulus);
Fast power modulus calculation forBigInt operands.
Parameters:
BigIntbasetheBigInt is basic operands.
BigIntexponenttheBigInt is power exponent of base.
BigIntmodulustheBigInt is modules to be modular of base ^ exponent.
Returns:
The power modulus value of (base ^ exponent) % modulus.
Examples:
for powmod
BigIntbase = BigInt("123456789012345678901234567890");BigIntexponent = BigInt("1234567890123456789012345678901234567");BigIntmodulus = BigInt("1234567");BigInt result =powmod(base,exponent,modulus);writeln(result);// 359079
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 17:58:36 2026

[8]ページ先頭

©2009-2026 Movatter.jp