C# BigInteger – Working with Large Numbers

Working with large numbers was always a problem for any programmer – no one enjoys doing math operations using numbers stored in arrays, but once .NET Framework 4 came out it also included a new type BigInteger.
It’s inside structure is similar to an array of int – so it’s immutable (this means memory will be reallocated each time) but the main advantage is that it is not limited to a minimum or maximum value – so it will take as much memory as it needs.

1. Add a reference

To be able to use it, you need to add a reference: References from Solution Explorer -> Add Reference -> .NET and look for System.Numerics.
Then add to your source:
Now you can use BigInteger in your program.

2. How to use it

Even if BigInteger is a ‘new’ data type, it is perfectly compatible with the other numeric classes – but the number will be stored as an integer.
Here I wrote a small example demonstrating that it’s actually unlimited – the following program calculates the powers of 2, using a BigInteger.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Numerics;
namespace powers
{
    class Program
    {
        
        static void Main(string[] args)
        {
            BigInteger n = 1;
            while (true)
            {
                Console.WriteLine(n);
                n *= 2;
                
                //the next line is optional, it just slows down the process
                System.Threading.Thread.Sleep(20);
                
            }
        }
    }
}
Previous
Next Post »