Big, unlimited integers in C#
gpeipman
14.1K views
BigInteger in C#
There are situations when calculations in application are done on integers bigger than what int and its relatives can carry out. For these situations there is class BigInteger in System.Numerics namespace. BigInteger has many operations available through defined operators and static methods. Check the references section for more information about it.
The following example shows how to use big integers and perform some operations on them.
Click Run to run the demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Numerics;
namespace BigIntegerCore
{
public class Program
{
public static void Main(string[] args)
{
var bigInteger1 = BigInteger.Parse("9930203828488338200022210011110239939391203");
var bigInteger2 = BigInteger.Parse("-130203828488338200022210011110239939391203");
Console.WriteLine("Add: " + (bigInteger1 + 1));
Console.WriteLine("Add: " + (bigInteger1 + bigInteger2));
Console.WriteLine("Multiply: " + (bigInteger1 * bigInteger2));
Console.WriteLine("Divide: " + (bigInteger1 / bigInteger2));
Console.WriteLine("Square: " + BigInteger.Pow(bigInteger2, 2));
Console.WriteLine("Greatest common divisor: " + BigInteger.GreatestCommonDivisor(bigInteger1, bigInteger2));
}
}
}
System.Numerics has also some other non-regular types available as Complex, few vectors and matrices.
References
- BigInteger Structure (MSDN)
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.