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?
- Int64 won't suffice? Could you give an example of an arithmetic action you'd like to perform?Yvo– Yvo2010-02-13 22:14:20 +00:00Commented Feb 13, 2010 at 22:14
- 1Will System.Decimal be large enough for you? The largest value that can be represented with it is 79,228,162,514,264,337,593,543,950,335.jjxtra– jjxtra2010-02-13 22:16:10 +00:00Commented Feb 13, 2010 at 22:16
- 1"Humongous" is not actually a useful description. Are we talking about numbers with twenty digits, a thousand digits, a million digits, a billion digits or more than a billion digits? The answer to your question will be different for each.Eric Lippert– Eric Lippert2010-02-14 17:44:26 +00:00Commented Feb 14, 2010 at 17:44
- How about a few hundred digits?Maxim Zaslavsky– Maxim Zaslavsky2010-03-17 14:56:11 +00:00Commented Mar 17, 2010 at 14:56
5 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#.
Comments
.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.
Comments
The GNU MP bignum library is one of the fastest around. there's a .NET wrapper for it http://gnumpnet.codeplex.com/
Here's another bignum library for .NET with source.
Comments
Big Integer class that I've used many times for cryptography projects (where extremely large numbers are needed). Works great.
Comments
In dotnet version above 4.0, System.Numerics.BigInteger will help you for this problem.
if you get assembly reference error using the above syntax, then add reference using
http://www.dllme.com/dll/files/system_numerics_dll.html.
Hope this will help you..!