C++ 中的双整数精度乘法
是否有任何标准的 C++ 方法(例如类库)提供双精度整数乘法?我的意思是:给定两个无符号整数 a,b,它们的乘法应该给我一个由两个无符号整数 {c, d} 组成的数组,这样 a*b = c + d*(UINT_MAX+1) ?
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) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
GMP 可能是一个选项
GMP could be an option
如果您仅限于 C++ 标准库,那么答案是否定的,没有这样的预定义类型。您可以在此处进行确认。 @DumbCoder 建议了一个替代方案
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
我不确定这是否可以解决问题,但作为一个粗略的内置解决方案,您可以尝试使用
unsigned long long int
,它是一个 64 位整数。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.BigInt 类允许您使用任意精度整数。
The BigInt class lets you work with arbitrary precision integers.
你走在正确的轨道上,将乘法分成几部分,除了 h=(UINT_MAX+1)/2 的地方,它应该是 h=sqrt(UINT_MAX+1) 。如果您有 32 位整数,例如 h=0x10000。乘以这样一个常数与左移多个位相同,因此您的等式变为:
由于每个分量都是 16 位或更少,因此每次乘法都保证适合无符号 32 位结果。
要将多精度值相加,请参阅如何如果我的编译器不支持 C 或 C++ 中的 128 位整数加法和减法?
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:
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?