這個系列主要是記一下目前效率較高或者比較出名的一些算法.算法
Karatsuba multiplication:spa
x=5678 then: a=56 b=67orm
y=1234 c=12 d=34ip
setps: it
1: a*c = 672 ①io
2: b*d=2652 ②class
3: (a+b)(c+d)=6164 ③效率
4: ③-②-①=2840call
5: 6720000 + 2652+284000 = 7006652計算機
Recursive algorithm:
whrite: x= 10n/2 a+b y= 10 n/2 c+d
then x*y = 10nac+10n/2(ad+bc)+bd 這裏,咱們須要作4次乘法,在計算機中的cost並不理想,因此用到一個
Gauss's trick:
step1: recursively compute ac
step2: recurisively compute bd
step3: recurisively compute (a+c)*(c+d) then
ad+bc = (a+c)*(c+d) - ac - bd
upshot:only 3 recursive multiply calls.
note: 這裏的n表示位數, 好比x是6位數,n=6, n/2=3,若是x=7,則n/2取4.
保留一個問題,這個是我比較困惑的, 若是x和y位數相差比較大這個算法還能不能用, 好比x是7位數,y是三位數,但願大神解答!
在計算機裏,少作一次乘法的效率會提升很多,對於給定的n位大數,算法的複雜度不超過3nlog3 ≈ 3n1.585, 通常給定N位數,複雜度是n平方。