How to use large numbers in C#

All primitive type in every language have a limit as to what and how much they can store. We will be talking specifically about integers for now. Everyone has used different sizes of integral types to store a number, the most common being int. Here is a brief list of integral types we use on a daily basis.

byte  0 – 255
short -32,768 to 32,767
int -2,147,483,648 to 2,147,483,647
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

If you know you are only going to use positive number, then you can use the unsigned version of each type, which removes negative values and doubles the positive values. However this does not apply for the byte value type, by default a byte is unsigned.

sbyte  -128 to 127
ushort 0 to 65,535
uint 0 to 4,294,967,295
ulong 0 to 18,446,744,073,709,551,615

As you can see if you can get a really big number by just using ulong, but what would use if you want a bigger number?

BigInteger

BigInteger is what you would use to store values bigger than ulong.MaxValue or less than  long.MinValue.

You must add the assembly reference System.Numerics  to the solution and the statement using System.Numerics.

This will result in the value 2423422568875769689.

As you saw, you can do regular arithmetic on BigInteger values. If you do x.GetType() you will see that this will result in a BigInteger type.

For more information on BigInteger check out the Microsoft Documentation.

Bookmark and Share

1 Response

  1. Hosting June 4, 2016 / 7:15 pm

    Firstly, I know that I should be looking for more efficient ways of calculation so as to avoid the large number problem.

Leave a Reply

Your email address will not be published. Required fields are marked *