ZetCode

C# BigInteger

last modified November 15, 2026

This article shows how to work with arbitrarily large integers in C# using the BigInteger type.

BigInteger is an immutable struct from the System.Numerics namespace that represents a signed integer of any size. The built-in integer types have fixed ranges; the largest one, UInt128, stops at about 3.4×1038. A BigInteger grows as needed and is limited only by the available memory.

We use BigInteger for exact computations with very large numbers: factorials, combinatorics, cryptography, arbitrary-precision counters, or parsing numeric identifiers that do not fit into long. The price is speed: every operation allocates a new value and works on an array of digits, so BigInteger is much slower than int or long.

The type supports the usual arithmetic, comparison, and bitwise operators, converts implicitly from all built-in integer types, and implements the generic math interfaces such as INumber<T>.

Overflows

An arithmetic overflow occurs when a calculation produces a value that is greater than the given data type can store. With built-in integer types, the result silently wraps around.

Program.cs
using System.Numerics;

Console.WriteLine(int.MaxValue);
Console.WriteLine(long.MaxValue);
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(UInt128.MaxValue);

Console.WriteLine("-----------------------");

UInt128 max = UInt128.MaxValue;

Console.WriteLine(max + 1);
Console.WriteLine(max + 2);
Console.WriteLine(max + 3);

Console.WriteLine("-----------------------");

Console.WriteLine((BigInteger)max + 1);
Console.WriteLine((BigInteger)max + 2);
Console.WriteLine((BigInteger)max + 3);

We add small values to the largest UInt128 number, first with UInt128 arithmetic and then with BigInteger.

Console.WriteLine(int.MaxValue);
Console.WriteLine(long.MaxValue);
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(UInt128.MaxValue);

For comparison, we print the maximum values of the int, long, ulong, and UInt128 types.

Console.WriteLine(max + 1);
Console.WriteLine(max + 2);
Console.WriteLine(max + 3);

The additions overflow and wrap around to 0, 1, and 2. Integer arithmetic is unchecked by default; in a checked context, the operation would throw an OverflowException instead.

Console.WriteLine((BigInteger)max + 1);
Console.WriteLine((BigInteger)max + 2);
Console.WriteLine((BigInteger)max + 3);

To get the correct results, we convert the first operand to BigInteger. The other operand is then converted implicitly and the whole computation is done with BigInteger.

$ dotnet run
2147483647
9223372036854775807
18446744073709551615
340282366920938463463374607431768211455
-----------------------
0
1
2
-----------------------
340282366920938463463374607431768211456
340282366920938463463374607431768211457
340282366920938463463374607431768211458

Creating BigInteger values

There is no literal for BigInteger. Values are created from the built-in numeric types, parsed from strings, or built from byte arrays.

Program.cs
using System.Globalization;
using System.Numerics;

BigInteger a = 1234567890;
BigInteger b = long.MaxValue;
BigInteger c = UInt128.MaxValue;

BigInteger d = BigInteger.Parse("123456789012345678901234567890");
BigInteger e = new(1e30);
BigInteger f = (BigInteger)12345.99m;

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(e);
Console.WriteLine(f);

Console.WriteLine(BigInteger.Zero);
Console.WriteLine(BigInteger.One);
Console.WriteLine(BigInteger.MinusOne);

if (BigInteger.TryParse("12x45", out BigInteger g))
{
    Console.WriteLine(g);
}
else
{
    Console.WriteLine("12x45 is not a valid number");
}

BigInteger h1 = BigInteger.Parse("FF", NumberStyles.HexNumber);
BigInteger h2 = BigInteger.Parse("0FF", NumberStyles.HexNumber);

Console.WriteLine($"FF -> {h1}, 0FF -> {h2}");

The example shows several ways of creating BigInteger values.

BigInteger a = 1234567890;
BigInteger b = long.MaxValue;
BigInteger c = UInt128.MaxValue;

All built-in integer types, including Int128 and UInt128, convert to BigInteger implicitly, because no information can be lost.

BigInteger d = BigInteger.Parse("123456789012345678901234567890");

The largest integer literal in C# is ulong.MaxValue, which is 18446744073709551615. Larger values must be parsed from their string representation with BigInteger.Parse.

BigInteger e = new(1e30);
BigInteger f = (BigInteger)12345.99m;

A BigInteger can be created from a double or a decimal with a constructor or an explicit cast. The fractional part is truncated. The output shows that 1e30 is not exactly 1030: BigInteger keeps the exact binary value of the double, including its rounding error.

Console.WriteLine(BigInteger.Zero);
Console.WriteLine(BigInteger.One);
Console.WriteLine(BigInteger.MinusOne);

The type provides static properties for the three most common values.

if (BigInteger.TryParse("12x45", out BigInteger g))

TryParse returns false instead of throwing a FormatException for invalid input.

BigInteger h1 = BigInteger.Parse("FF", NumberStyles.HexNumber);
BigInteger h2 = BigInteger.Parse("0FF", NumberStyles.HexNumber);

When parsing hexadecimal strings, BigInteger uses two's complement: if the highest bit of the first digit is set, the number is negative. So FF is -1, and we need a leading zero to get 255.

$ dotnet run
1234567890
9223372036854775807
340282366920938463463374607431768211455
123456789012345678901234567890
1000000000000000019884624838656
12345
0
1
-1
12x45 is not a valid number
FF -> -1, 0FF -> 255

Arithmetic operations

BigInteger overloads the arithmetic operators. Each operator also has an equivalent static method, which is useful in languages without operator overloading.

Program.cs
using System.Numerics;

BigInteger a = BigInteger.Parse("12423523432222288811111000");
BigInteger b = BigInteger.Parse("98765432109876543210");

Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
Console.WriteLine(-a);

Console.WriteLine("-----------------------");

Console.WriteLine(BigInteger.Add(a, b));
Console.WriteLine(BigInteger.Subtract(a, b));
Console.WriteLine(BigInteger.Multiply(a, b));
Console.WriteLine(BigInteger.Divide(a, b));
Console.WriteLine(BigInteger.Remainder(a, b));
Console.WriteLine(BigInteger.Negate(a));

Console.WriteLine("-----------------------");

BigInteger n = 10;
n += 5;
n *= n;
n++;

Console.WriteLine(n);

The program performs basic arithmetic with two large values.

Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
Console.WriteLine(-a);

We add, subtract, multiply, and divide the values, compute the remainder, and negate the first value. Division is integer division; the fractional part is discarded.

Console.WriteLine(BigInteger.Add(a, b));
Console.WriteLine(BigInteger.Subtract(a, b));

The static Add, Subtract, Multiply, Divide, Remainder, and Negate methods give the same results as the operators.

BigInteger n = 10;
n += 5;
n *= n;
n++;

Compound assignment and the increment operator work too. Since BigInteger is immutable, each of these statements creates a new value and assigns it to the variable.

$ dotnet run
12423622197654398687654210
12423424666790178934567790
1227014660110610883679164137831137319606310000
125788
17257985138193811520
-12423523432222288811111000
-----------------------
12423622197654398687654210
12423424666790178934567790
1227014660110610883679164137831137319606310000
125788
17257985138193811520
-12423523432222288811111000
-----------------------
226

Division and remainder

The BigInteger.DivRem method computes the quotient and the remainder in one call.

Program.cs
using System.Numerics;

BigInteger z1 = BigInteger.Parse("9640282333924329381111174611241768210411");
BigInteger z2 = BigInteger.Parse("340282366920938463463374607431768210428");

(BigInteger q, BigInteger r) = BigInteger.DivRem(z1, z2);

Console.WriteLine($"quotient: {q}");
Console.WriteLine($"remainder: {r}");
Console.WriteLine(z1 == q * z2 + r);

Console.WriteLine("-----------------------");

BigInteger x = -7;
BigInteger y = 2;

Console.WriteLine($"{x} / {y} = {x / y}");
Console.WriteLine($"{x} % {y} = {x % y}");

BigInteger m = (x % y + y) % y;
Console.WriteLine($"{x} mod {y} = {m}");

Console.WriteLine("-----------------------");

try
{
    Console.WriteLine(z1 / BigInteger.Zero);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine(ex.Message);
}

The example divides two large values, shows how the remainder behaves for negative numbers, and divides by zero.

(BigInteger q, BigInteger r) = BigInteger.DivRem(z1, z2);

DivRem returns a tuple, which we deconstruct into two variables. We then verify that the dividend equals the quotient times the divisor plus the remainder.

Console.WriteLine($"{x} / {y} = {x / y}");
Console.WriteLine($"{x} % {y} = {x % y}");

Like the built-in types, BigInteger division truncates toward zero, and the remainder takes the sign of the dividend. -7 divided by 2 is -3 with a remainder of -1.

BigInteger m = (x % y + y) % y;

If we need the mathematical modulo, which is never negative for a positive divisor, we add the divisor and take the remainder again.

Console.WriteLine(z1 / BigInteger.Zero);

Division by zero throws a DivideByZeroException.

$ dotnet run
quotient: 28
remainder: 112376060138052404136685603152258318427
True
-----------------------
-7 / 2 = -3
-7 % 2 = -1
-7 mod 2 = 1
-----------------------
Attempted to divide by zero.

Pow, ModPow, and GreatestCommonDivisor

The BigInteger.Pow method raises a value to an int power. BigInteger.ModPow computes a power modulo a number and GreatestCommonDivisor returns the greatest common divisor of two values.

Program.cs
using System.Numerics;

BigInteger p = BigInteger.Pow(2, 200);
Console.WriteLine(p);

BigInteger n = BigInteger.Pow(long.MaxValue, 2);
Console.WriteLine(n);

Console.WriteLine("-----------------------");

BigInteger res = BigInteger.ModPow(7, BigInteger.Pow(10, 18), 1_000_000_007);
Console.WriteLine(res);

Console.WriteLine("-----------------------");

BigInteger a = BigInteger.Parse("123456789012345678901234567890");
BigInteger b = BigInteger.Parse("987654321098765432109876543210");

BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b);
BigInteger lcm = a / gcd * b;

Console.WriteLine($"gcd: {gcd}");
Console.WriteLine($"lcm: {lcm}");

The program computes large powers, a modular power, and the greatest common divisor and least common multiple of two numbers.

BigInteger p = BigInteger.Pow(2, 200);

We compute 2200, a number with 61 digits.

BigInteger res = BigInteger.ModPow(7, BigInteger.Pow(10, 18), 1_000_000_007);

ModPow computes 71018 mod 1000000007 without computing the power itself, which would not fit into memory. It uses repeated squaring and keeps the intermediate results small. Modular exponentiation is the core operation of RSA and other public-key algorithms.

BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b);
BigInteger lcm = a / gcd * b;

There is no built-in method for the least common multiple, but we can compute it from the greatest common divisor. We divide before multiplying to keep the intermediate value small.

$ dotnet run
1606938044258990275541962092341162602522202993782792835301376
85070591730234615847396907784232501249
-----------------------
259616729
-----------------------
gcd: 9000000000900000000090
lcm: 13548070124980948012498094801236261410

Factorial and Fibonacci

Factorials and Fibonacci numbers grow very fast and overflow long quickly: 21! and F(93) are already too large. BigInteger computes them exactly.

Program.cs
using System.Numerics;

BigInteger Factorial(int n)
{
    BigInteger res = BigInteger.One;

    for (int i = 2; i <= n; i++)
    {
        res *= i;
    }

    return res;
}

BigInteger Fibonacci(int n)
{
    BigInteger a = 0, b = 1;

    for (int i = 0; i < n; i++)
    {
        (a, b) = (b, a + b);
    }

    return a;
}

BigInteger f100 = Factorial(100);
string digits = f100.ToString();

Console.WriteLine(f100);
Console.WriteLine($"100! has {digits.Length} digits");
Console.WriteLine($"trailing zeros: {digits.Length - digits.TrimEnd('0').Length}");

Console.WriteLine("-----------------------");

BigInteger fib = Fibonacci(300);

Console.WriteLine(fib);
Console.WriteLine($"F(300) has {fib.ToString().Length} digits");

We compute 100! and the 300th Fibonacci number.

BigInteger res = BigInteger.One;

for (int i = 2; i <= n; i++)
{
    res *= i;
}

The factorial is the product of all integers from 1 to n. The int loop variable is converted implicitly in the multiplication.

(a, b) = (b, a + b);

The Fibonacci function keeps the last two numbers and advances them with a tuple assignment.

string digits = f100.ToString();

To count the digits, we convert the number to a string. The trailing zeros come from the factors 10, 20, 25, and so on.

$ dotnet run
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
100! has 158 digits
trailing zeros: 24
-----------------------
222232244629420445529739893461909967206666939096499764990979600
F(300) has 63 digits

Properties and number theory helpers

BigInteger has properties that test the value, and static methods inherited from the generic math interfaces that work with bits and logarithms.

Program.cs
using System.Numerics;

BigInteger n = BigInteger.Pow(2, 100);

Console.WriteLine(n);
Console.WriteLine($"IsZero: {n.IsZero}");
Console.WriteLine($"IsOne: {n.IsOne}");
Console.WriteLine($"IsEven: {n.IsEven}");
Console.WriteLine($"IsPowerOfTwo: {n.IsPowerOfTwo}");
Console.WriteLine($"Sign: {n.Sign}");
Console.WriteLine($"GetBitLength: {n.GetBitLength()}");
Console.WriteLine($"GetByteCount: {n.GetByteCount()}");
Console.WriteLine($"Log10: {BigInteger.Log10(n):F4}");
Console.WriteLine($"Log2: {BigInteger.Log2(n)}");
Console.WriteLine($"TrailingZeroCount: {BigInteger.TrailingZeroCount(n)}");
Console.WriteLine($"PopCount: {BigInteger.PopCount(n)}");

Console.WriteLine("-----------------------");

BigInteger m = -12345;

Console.WriteLine($"Sign: {m.Sign}");
Console.WriteLine($"Abs: {BigInteger.Abs(m)}");
Console.WriteLine($"IsNegative: {BigInteger.IsNegative(m)}");

The program examines 2100 and a negative value.

Console.WriteLine($"IsZero: {n.IsZero}");
Console.WriteLine($"IsOne: {n.IsOne}");
Console.WriteLine($"IsEven: {n.IsEven}");
Console.WriteLine($"IsPowerOfTwo: {n.IsPowerOfTwo}");
Console.WriteLine($"Sign: {n.Sign}");

These are instance properties. Sign is -1, 0, or 1. The tests are faster than the equivalent comparisons, for example IsEven checks a single bit instead of computing n % 2.

Console.WriteLine($"GetBitLength: {n.GetBitLength()}");
Console.WriteLine($"GetByteCount: {n.GetByteCount()}");

GetBitLength returns the number of bits needed to store the value in two's complement, including the sign bit, which is why 2100 needs 101 bits. GetByteCount returns the length of the array produced by ToByteArray.

Console.WriteLine($"Log10: {BigInteger.Log10(n):F4}");
Console.WriteLine($"Log2: {BigInteger.Log2(n)}");

Log10 and Log return a double, while Log2 returns the integer part of the binary logarithm as a BigInteger. The integer part of Log10 plus one is the number of decimal digits.

Console.WriteLine($"TrailingZeroCount: {BigInteger.TrailingZeroCount(n)}");
Console.WriteLine($"PopCount: {BigInteger.PopCount(n)}");

TrailingZeroCount counts the zero bits at the end and PopCount counts the set bits.

Console.WriteLine($"Abs: {BigInteger.Abs(m)}");
Console.WriteLine($"IsNegative: {BigInteger.IsNegative(m)}");

Abs returns the absolute value and IsNegative tests the sign.

$ dotnet run
1267650600228229401496703205376
IsZero: False
IsOne: False
IsEven: True
IsPowerOfTwo: True
Sign: 1
GetBitLength: 101
GetByteCount: 13
Log10: 30.1030
Log2: 100
TrailingZeroCount: 100
PopCount: 1
-----------------------
Sign: -1
Abs: 12345
IsNegative: True

Comparing and sorting

BigInteger implements IComparable<BigInteger> and the comparison operators. It can be compared with built-in integer types directly.

Program.cs
using System.Numerics;

List<BigInteger> vals =
[
    BigInteger.Parse("98765432109876543210"),
    -5,
    BigInteger.Pow(10, 25),
    0,
    long.MaxValue,
];

vals.Sort();
Console.WriteLine(string.Join(Environment.NewLine, vals));

Console.WriteLine("-----------------------");

BigInteger a = vals[0];
BigInteger b = vals[^1];

Console.WriteLine(a < b);
Console.WriteLine(a.CompareTo(b));
Console.WriteLine(BigInteger.Compare(b, a));
Console.WriteLine(a == 0);

Console.WriteLine(BigInteger.Max(a, b));
Console.WriteLine(BigInteger.Min(a, b));
Console.WriteLine(BigInteger.Clamp(BigInteger.Pow(10, 30), 0, b));

The example sorts a list of values and compares two of them.

vals.Sort();

Because the type implements IComparable<BigInteger>, List.Sort works without a custom comparer.

Console.WriteLine(a < b);
Console.WriteLine(a.CompareTo(b));
Console.WriteLine(BigInteger.Compare(b, a));
Console.WriteLine(a == 0);

We compare the smallest and the largest value with an operator, with the CompareTo instance method, and with the static Compare method. In a == 0, the integer is converted to BigInteger implicitly.

Console.WriteLine(BigInteger.Max(a, b));
Console.WriteLine(BigInteger.Min(a, b));
Console.WriteLine(BigInteger.Clamp(BigInteger.Pow(10, 30), 0, b));

Max and Min return the larger and the smaller value; Clamp restricts a value to a range.

$ dotnet run
-5
0
9223372036854775807
98765432109876543210
10000000000000000000000000
-----------------------
True
-1
1
False
10000000000000000000000000
-5
10000000000000000000000000

Converting and formatting

Conversions from BigInteger to built-in types are explicit, because the value may not fit. ToString supports the standard numeric format strings, and ToByteArray exposes the binary representation.

Program.cs
using System.Numerics;

BigInteger small = 1_000_000;
BigInteger big = BigInteger.Pow(10, 20);

long l = (long)small;
double d = (double)big;

Console.WriteLine(l);
Console.WriteLine(d);

try
{
    long l2 = (long)big;
    Console.WriteLine(l2);
}
catch (OverflowException ex)
{
    Console.WriteLine(ex.Message);
}

Console.WriteLine("-----------------------");

Console.WriteLine(big.ToString("N0"));
Console.WriteLine(big.ToString("X"));
Console.WriteLine(big.ToString("E3"));
Console.WriteLine(new BigInteger(255).ToString("X"));
Console.WriteLine(new BigInteger(-1).ToString("X"));

Console.WriteLine("-----------------------");

byte[] bytes = big.ToByteArray();
Console.WriteLine(Convert.ToHexString(bytes));

byte[] be = big.ToByteArray(isUnsigned: true, isBigEndian: true);
Console.WriteLine(Convert.ToHexString(be));

BigInteger back = new(be, isUnsigned: true, isBigEndian: true);
Console.WriteLine(back == big);

The program converts BigInteger values to other types, strings, and byte arrays.

long l = (long)small;
double d = (double)big;

Explicit casts convert the values to long and double. Converting to double may lose precision but does not throw.

long l2 = (long)big;

1020 does not fit into long. Unlike casts between built-in types, the cast always throws an OverflowException, even in an unchecked context.

Console.WriteLine(big.ToString("N0"));
Console.WriteLine(big.ToString("X"));
Console.WriteLine(big.ToString("E3"));
Console.WriteLine(new BigInteger(255).ToString("X"));
Console.WriteLine(new BigInteger(-1).ToString("X"));

The N0 format adds group separators, X produces hexadecimal, and E3 the exponential notation. The hexadecimal output uses two's complement, like parsing: 255 is formatted as 0FF so that it is not read back as a negative number, and -1 is F.

byte[] bytes = big.ToByteArray();

By default, ToByteArray returns the two's complement representation in little-endian order, so the least significant byte comes first.

byte[] be = big.ToByteArray(isUnsigned: true, isBigEndian: true);

The overload with named parameters produces the unsigned big-endian form, which is used by most file formats and network protocols. The matching constructor creates the value back from the bytes.

$ dotnet run
1000000
1E+20
Value was either too large or too small for an Int64.
-----------------------
100,000,000,000,000,000,000
56BC75E2D63100000
1.000E+020
0FF
F
-----------------------
000010632D5EC76B05
056BC75E2D63100000
True

Integer square root

BigInteger has no square root method; Math.Sqrt works with double and loses precision for large numbers. We can compute the integer square root with Newton's method.

Program.cs
using System.Numerics;

BigInteger ISqrt(BigInteger n)
{
    if (n < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(n));
    }

    if (n < 2)
    {
        return n;
    }

    BigInteger x = BigInteger.One << (int)((n.GetBitLength() + 1) / 2);

    while (true)
    {
        BigInteger y = (x + n / x) >> 1;

        if (y >= x)
        {
            return x;
        }

        x = y;
    }
}

BigInteger two = 2 * BigInteger.Pow(10, 100);
BigInteger root = ISqrt(two);

Console.WriteLine(root);
Console.WriteLine(root * root <= two && (root + 1) * (root + 1) > two);

BigInteger sq = BigInteger.Pow(BigInteger.Parse("123456789123456789"), 2);
Console.WriteLine(ISqrt(sq));

The ISqrt function returns the largest integer whose square is not greater than n.

BigInteger x = BigInteger.One << (int)((n.GetBitLength() + 1) / 2);

We start with a power of two that is surely greater than the root. Its exponent is half the bit length of n, rounded up. The shift operators work on BigInteger like on built-in types.

BigInteger y = (x + n / x) >> 1;

if (y >= x)
{
    return x;
}

Each Newton step averages x and n / x. The estimates decrease toward the root; when they stop decreasing, we have the result. The number of correct digits roughly doubles in every step.

BigInteger two = 2 * BigInteger.Pow(10, 100);
BigInteger root = ISqrt(two);

The square root of 2×10100 gives the first 51 digits of the square root of two.

$ dotnet run
141421356237309504880168872420969807856967187537694
True
123456789123456789

Generic math

BigInteger implements INumber<BigInteger>, so it can be used with generic algorithms written for any number type.

Program.cs
using System.Numerics;

T Sum<T>(IEnumerable<T> vals) where T : INumber<T>
{
    T total = T.Zero;

    foreach (T val in vals)
    {
        total += val;
    }

    return total;
}

int[] ints = [int.MaxValue, 1];
long[] longs = [int.MaxValue, 1];
BigInteger[] bigs = [BigInteger.Pow(10, 30), 1];

Console.WriteLine(Sum(ints));
Console.WriteLine(Sum(longs));
Console.WriteLine(Sum(bigs));

The generic Sum function adds the elements of any numeric sequence.

T Sum<T>(IEnumerable<T> vals) where T : INumber<T>

The INumber<T> constraint gives access to T.Zero and the + operator.

Console.WriteLine(Sum(ints));
Console.WriteLine(Sum(longs));
Console.WriteLine(Sum(bigs));

We call the same function with three types. The int sum overflows, the long sum has enough range, and the BigInteger sum is exact for any size.

$ dotnet run
-2147483648
2147483648
1000000000000000000000000000001

Source

BigInteger struct - .NET API

In this article we have worked with arbitrarily large integers in C# using BigInteger. See also the integer types, Decimal, floating-point types, Math, and operator overloading tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.