开发者

Working with numbers larger than max decimal value

I'm working with the product of the first 26 prime numbers. This requires more than 52 bits of precision, which I believe is the max a double can handle, and more than the 28-29 significant digits a decimal can provide. So what would be some strategies for performing multiplication and division on numbers this large?

Also, what would the performance impacts be of whatever hoops I'd have to jump through to make this happen?

The product of the first 22 prime numbers (the most I can multiply together on my calculator without dropping into scientific mode) is:

10,642,978,845,819,148,849,204,664,294,430

The product of the last four is

72,370,439

When multiplied together, I get:

7.7023705133964511682328635583552e+38

The performance impacts are especially important here, because we're essentially trying to resolve the question of whether a prime-number string comparison solution is faster in practice than a straight comparison of characters. The post which prompted this investigation is here. Processors are optimized for floating-point calculations; ideally I'd want to leverage as much of t开发者_如何学编程hat optimization in whatever solution I end up with.

TIA!

James

PS: The code I do have is for a competing solution; I don't think the prime number solution can possibly be faster, but I'm trying to give it the fairest chance I can.


You can use BigInteger in C#4.0. For older versions, I think you need an open source library such as this one


I read the post you linked to, about the interview question. Since you're only multiplying and dividing these large integers, a huge optimization is to keep them in their prime-factorized form. Each large integer is an array [0..25] of ints, each element representing the exponent of the nth prime in the factorization. To multiply two large integers in this form, simply add the exponents element-by-element; to divide, subtract exponents.

But you will see this is equivalent to tabulating character counts on the two strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜