Is 开发者_开发知识库there any standard C++ way (e.g. class library) which provides integer multiplication with double precision? What I mean is: given two unsigned int's a,b the multiplication of them should give me an array of two unsigned int's {c, d} such that a*b = c + d*(UINT_MAX+1) ?
GMP could be an option
If you are restricted to the C++ standard libraries, the answer is no, there is no such predefined type. You can confirm that here. @DumbCoder suggested an alternative
I'm not sure if this solves the problem, but as a crude built-in solution, you may try to use unsigned long long int
, which is a 64-bit integer.
The BigInt class lets you work with arbitrary precision integers.
You were on the right track with splitting up the multiplication into pieces, except where you had h=(UINT_MAX+1)/2 it should be h=sqrt(UINT_MAX+1). If you have 32-bit integers for example h=0x10000. Multiplying by such a constant is the same as shifting left by a number of bits, so your equation becomes:
a0 = a & 0xffff;
a1 = a >> 16;
b0 = b & 0xffff;
b1 = b >> 16;
a*b = a0*b0 + ((a1*b0)<<16 + (a0*b1)<<16) + (a1*b1)<<32
Since each component is 16 bits or less, each multiplication is guaranteed to fit into an unsigned 32 bit result.
For adding multiple-precision values together, see How can I add and subtract 128 bit integers in C or C++ if my compiler does not support them?
精彩评论