Naive (grade school) multiplication has a running time of O(n^2).
Python uses Karatsuba multiplication whose running time is O(n^1.585).
Karatsuba Multiplication Algorithm
Also, a combination of Karatsuba, Toom-Cook, and Nussbaumer convolution can be used to get a running time of O(n*ln(n)).
======================
Python 为什么使用“复杂度更高”的Karatsuba Multiplication而不是大家常念叨的O(nlogn)的FFT大法?
(1)
In practice the Schönhage–Strassen algorithm starts to outperform
older methods such as Karatsuba and Toom–Cook multiplication for
numbers beyond 2**2**15 to 2**2**17 (10,000 to 40,000 decimal digits). [1](2) 讲道理的话,python使用者用的“大数”哪里会超过10000位。。。
[1] Schönhage
=======================
Karatsuba Multiplication的源码?
yes, talk is cheap, plz search it (python) on github. [2]
其实可以看到,当其中任意一个数的位数很少的时候,python是用朴素乘法的。。。
这说明朴素乘法在该情况下更快。。
[2] cpython/longobject.c at master · python/cpython · GitHub
=======================
Karatsuba Multiplication什么时候加进python的?
2002年 [3]
[3] Issue 560379: Karatsuba multiplication
=======================
既然当位数很少的时候,Python用更快的朴素乘法,那为什么不加一个判断条件,当位数超级多的时候用FFT这种方法?
I'm far from sure that such a patch would be accepted. :-) Indeed,
Tim Peters has been heard to mention that if he were to do it all
again, he probably wouldn't even have implemented Karatsuba [4].
Asymptotically fast integer multiplication is a specialist need that's
already available in 3rd-party Python libraries (gmpy). IMO, it's not
appropriate to include it in a general-purpose programming language,
and the burden of maintaining such code would outweigh the benefits.
One thing that has been considered in the past is making it possible
to use GMP directly for Python's implementation of long integers; see
Victor Stinner's efforts in this direction [5]. Licensing concerns,
and the fact that Python's implementation is faster for small
integers, ended up killing this issue.
[4] [Python-Dev] Optionally using GMP to implement long if available
[5] Issue 1814: Victor Stinner's GMP patch for longs
=======================
Karatsuba算法的思想?复杂度怎么算的。。
分治,其实贴的链接里面提得挺多的了。。下面简单描述一下。
要算
,假设它们都是n位数。。把x和y都拆成2个n/2的部分
。
普通的算法是计算
,这样1次size为n的大数乘法 变成 4次size为n/2的大数乘法加上1次size为n/2的大数加法,这样得到的复杂度递推式是
,然后解这个递推式子得到复杂度
。
然而,其实我们只要求
而不必分别求它们,而且我们发现
,这样1次size为n的大数乘法就变成了 3次size为n/2的大数乘法加上3次size为n/2的大数加法(减法也当作加法),这样得到的复杂度递推式为
,使用主方法解这个递推式得到复杂度
。
========================
a combination of Karatsuba, Toom-Cook, and Nussbaumer convolution是什么?怎么combine?
不知道。这句话是GMP [6]的作者写的。有兴趣可以去看GMP的实现。:)
[6] The GNU MP Bignum Library