计算 BigInteger 的平方
我正在使用 .NET 4 的 System.Numerics.BigInteger 结构。
我需要计算非常大的数字的平方 (x2) - 数百万十进制数字。
如果 x 是 BigInteger,则:
x*x;
或 的
BigInteger.Pow(x,2);
时间复杂度是多少?
如何使用 .NET 4 BigInteger 以最快的方式乘以如此大的数字?是否有 Schönhage–Strassen 算法 的实现?
I'm using .NET 4's System.Numerics.BigInteger structure.
I need to calculate the square (x2) of very large numbers - millions of decimal digits.
If x
is a BigInteger
, What is the time complexity of:
x*x;
or
BigInteger.Pow(x,2);
?
How can multiply such big numbers in the fastest way using .NET 4 BigInteger? Is there an implementation for Schönhage–Strassen algorithm?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于你的人数有多大。正如维基百科页面告诉您的那样:
System.Numerics.BigInteger
使用 Karatsuba 算法 或标准教科书乘法,取决于数字的大小。 Karasuba 的时间复杂度为 O(n log2 3)。但如果您的数字小于上面引用的数字,那么您可能不会看到实施 Schönhage-Strassen 带来的加速。至于
Pow()
,它本身在计算过程中至少对数字进行一次平方(并且它通过简单地执行num * num
来实现这一点 - 所以我认为这不会是也更有效率。That depends on how large your numbers are. As the Wikipedia page tells you:
System.Numerics.BigInteger
uses the Karatsuba algorithm or standard schoolbook multiplication, depending on the size of the numbers. Karatsuba has a time complexity of O(n log2 3). But if your numbers are smaller than above quoted figures, then you likely won't see much speedup from implementing Schönhage–Strassen.As for
Pow()
this itself squares the number at least once during its calculations (and it does that by simply doingnum * num
– so I think this won't be more efficient, either.一种非常简单的实现方法是基于 FFT。由于将两个数字相乘相当于执行其系数的卷积,然后通过一次消除进位,因此您应该能够通过 FFT 方法(n = 位数)以 O(n log n) 运算进行卷积。
数值食谱有一章介绍这一点。对于如此大的数字来说,这绝对比分而治之的方法更快,比如唐叶。
A quite simple method to implement is based on FFT. Since multiplying two numbers amounts to perform a convolution of their coefficients followed by a pass to eliminate carries, you should be able to do the convolution in O(n log n) operations via FFT methods (n = number of digits).
Numerical recipes has a chapter on this. This is definitely faster than divide and conquer methods, like Karatsuba, for such big numbers.
首先,
System.Numerics.BigInteger
不使用 [Karatsuba算法],O(n 0.5 ),它使用标准教科书乘法 O(n 2 )。
通过此代码,您可以在短短 1.4 毫秒内乘以两个 30,000 位(大约 9000 个十进制数字)。
First of All,
System.Numerics.BigInteger
does NOT use the [Karatsubaalgorithm] with O(n 0.5 ) and it uses standard schoolbook multiplication O(n 2 ).
By this code you can Multiple two 30,000 bit (approximately 9000 decimal digit) in Just 1.4 millisecond.
您可以使用 GNU MP Bignum 库的 C# 包装器,它的速度可能与您一样快可以得到。对于纯 C# 实现,您可以尝试 IntX。
最快的乘法算法实际上是Fürer的算法,但我还没有找到它的任何实现。
You can use a C# wrapper for GNU MP Bignum Library, which is probably as fast as you can get. For pure C# implementation you could try IntX.
Fastest multiplication algorithm is actually Fürer's algorithm, but I haven't found any implementations for it.