Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How Should I Handle Arithmetic with Huge Numbers?

I'm writing an app which involves arithmetic with humongous numbers, with very many digits. I've previously written a class that simplifies handling big numbers by defining them as strings and then using slow arithmetic string functions. Is this the best way to do it? If not, how should I approach this problem? Does C# have anything built-in for such situations?

like image 382
Maxim Zaslavsky Avatar asked Feb 13 '10 22:02

Maxim Zaslavsky


2 Answers

If you can do it on .NET 4, System.Numeric.BigInteger can help. If you're on an older version of .NET, IntX will help you.

See also this this SO question on big integers in C#.

like image 153
Håvard S Avatar answered Nov 09 '22 03:11

Håvard S


.NET 4 will have this built in via the BigInteger type. This is claimed to be pretty well tuned and should perform very well.

For 3.5 and earlier, you can grab an implementation of BigInteger from the Dynamic Language Runtime sources. (See e.g. http://dlr.codeplex.com/sourcecontrol/changeset/view/40021?projectName=dlr#694008 and drill down into Src / Runtime / Microsoft.Dynamic / Math.) I don't know if this has been tuned as highly as the .NET 4 BigInteger type, but it should still be more efficient than your string version because it internally represents the big numbers using integral types and performs arithmetic using integer operations.

like image 40
itowlson Avatar answered Nov 09 '22 02:11

itowlson