Big integers in C#

2020-01-22 13:38发布

Currently I am borrowing java.math.BigInteger from the J# libraries as described here. Having never used a library for working with large integers before, this seems slow, on the order of 10 times slower, even for ulong length numbers. Does anyone have any better (preferably free) libraries, or is this level of performance normal?

13条回答
时光不老,我们不散
2楼-- · 2020-01-22 14:12

I reckon you could optimize the implementation if you perform all the operations on BigInts that are going to return results smaller than a native type (Eg. int64) on the native types and only deal with the big array if you are going to overflow.

edit This implementation on codeproject, seems only 7 times slower ... But with the above optimization you could get it to perform almost identically to native types for small numbers.

查看更多
贪生不怕死
3楼-- · 2020-01-22 14:12

You can also use the Math.Gmp.Native Nuget package that I wrote. Its source code is available on GitHub, and documentation is available here. It exposes to .NET all of the functionality of the GMP library which is known as a highly-optimized arbitrary-precision arithmetic library.

Arbitrary-precision integer are represented by the mpz_t type. Operations on these integers all begin with the mpz_ prefix. For examples, mpz_add or mpz_cmp. Source code examples are given for each operation.

查看更多
趁早两清
4楼-- · 2020-01-22 14:13

See the answers in this thread. You will need to use one of the third-party big integer libraries/classes available or wait for C# 4.0 which will include a native BigInteger datatype.

查看更多
Deceive 欺骗
5楼-- · 2020-01-22 14:14

I used Biginteger at a previous job. I don't know what kind of performance needs you have. I did not use it in a performance-intensive situation, but never had any problems with it.

查看更多
看我几分像从前
6楼-- · 2020-01-22 14:16

As of .NET 4.0 you can use the System.Numerics.BigInteger class. See documentation here: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

Another alternative is the IntX class.

IntX is an arbitrary precision integers library written in pure C# 2.0 with fast - O(N * log N) - multiplication/division algorithms implementation. It provides all the basic operations on integers like addition, multiplication, comparing, bitwise shifting etc.

查看更多
倾城 Initia
7楼-- · 2020-01-22 14:19

Here are several implementations of BigInteger in C#. I've used Mono's BigInteger implementation, works pretty fast (I've used it in CompactFramework)

Bouncy Castle

Mono

查看更多
登录 后发表回答