I'm writing a program that assigns prime numbers to each entry of a matrix and then I'll need to multiply some of them. The resulting number grows rapidly and I'm at a loss as to which type to use, as I'm getting "wrap-around" with long do开发者_开发知识库uble :S
All the help is appreciated.
-Pickel
Unless you're required to implement your own arbitrary precision type, use GMP. You'll want the mpz_t (integer) type. It's pretty well documented, and there are tutorials and StackOverflow questions you can look at.
You may have to implement your own big integer type. Check out:
BigInt
If it's just integers, there's long long int
(at least in C/C++). If we're talking about doubles... Use a BigDecimal class.
Assuming you are using "long double" as a type that it's a C or C++ assignment?
How big are your numbers?
Maximum value vs. size of long and double in .NET
discusses some related stuff but may be beyond the scope of your assignment
Generally speaking you need an arbitrary precision library:
http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic
But chances are that for purposes of an assignment you are not required to make things so complicated as to require the use of an APL
if it's an integer, use the BigInteger class (in Java or .NET)
if it's a floating point, use BigDecimal (only in java, .net still does not have a arbitrary precision floating number
if you're in C/C++, you have to create your own type
If you refuse to use a library, and don't want to invent your own big types, why don't you keep track of extra factors of 2, or something like that.
while ( mybignum > BIGNUM_THRESH )
{
twos++;
mybignum /= 2; // use >>=1 if you use an integer type (you said you used double so therefore the /=)
}
then print out your answers as mybignum * 2**twos
Take a 64 bit int for twos and you're safe up to 2^2^64
精彩评论