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:20

F# also ships with one. You can get it at Microsoft.FSharp.Math.

查看更多
Animai°情兽
3楼-- · 2020-01-22 14:23

This won't help you, but there was supposed to be a BigInteger class in .Net 3.5; it got cut, but from statements made at PDC, it will be in .Net 4.0. They apparently have spent a lot of time optimizing it, so the performance should be much better than what you're getting now.

Further, this question is essentially a duplicate of How can I represent a very large integer in .NET?

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

Yes, it will be slow, and 10x difference is about what I'd expect. BigInt uses an array to represent an arbitrary length, and all the operations have to be done manually (as opposed to most math which can be done directly with the CPU)

I don't even know if hand-coding it in assembly will give you much of a performance gain over 10x, that's pretty damn close. I'd look for other ways to optimize it--sometimes depending on your math problem there are little tricks you can do to make it quicker.

查看更多
地球回转人心会变
5楼-- · 2020-01-22 14:29

The System.Numerics.BigInteger class in .NET 4.0 is based on Microsoft.SolverFoundation.Common.BigInteger from Microsoft Research.

The Solver Foundation's BigInteger class looks very performant. I am not sure about which license it is released under, but you can get it here (download and install Solver Foundation and find the Microsoft.Solver.Foundation.dll).

查看更多
狗以群分
6楼-- · 2020-01-22 14:29

I'm not sure about the performance, but IronPython also has a BigInteger class. It is in the Microsoft.Scripting.Math namespace.

查看更多
地球回转人心会变
7楼-- · 2020-01-22 14:29

This may sound like a strange suggestion, but have you tested the decimal type to see how fast it works?

The decimal range is ±1.0 × 10^−28 to ±7.9 × 10^28, so it may still not be large enough, but it is larger than a ulong.

There was supposed to be a BigInteger class in .NET 3.5, but it got cut.

查看更多
登录 后发表回答