I want to improve timing of squaring for big numbers.
So I asked What is the fastest way to split a number into parts and What is the most efficient way to add zeros to end of a number with several answers posted.
Karatsuba multiplication must benefit from smaller size multiplication but mine suffer from this.
FastSquare[a_] := (TotalLen = IntegerLength[a]; If[TotalLen == 1, Return[a*a]]; e = Quotient[TotalLen, 2]; {A, B} = QuotientRemainder[a, 10^e]; Result = A*A*10^(2*e) + 2*A*B*10^(e) + B*B; Return[Result]) And timings are:
In[21]:= First[Timing[(2^200000000 + 1)^2]] Out[21]= 2.281 In[20]:= First[Timing[FastSquare[2^200000000 + 1]]] Out[20]= 15.86 (Debug) In[25]:= FastSquare[2^200000000 + 1]; // RuntimeTools`Profile Calls Time Evaluation 1 15.766 FastSquare[2^200000000+1]; 1 15.766 FastSquare[2^200000000+1] 1 15.75 FastSquare[a_] 1 15.75 TotalLen=IntegerLength[a];If[TotalLen==1,Return[a a]];e=Quotient[TotalLen,2];{A,B}=QuotientRemainder[a,10^e];Result=A A Power[<<2>>]+2 A B Power[<<2>>]+B B;Return[Result] 1 10.422 Result=A A 10^Times[<<2>>]+2 A B 10^e+B B 1 10.422 A A 10^(2 e)+2 A B 10^e+B B 1 5.328 {A,B}=QuotientRemainder[a,10^e] 1 5.328 QuotientRemainder[a,10^e] 1 5.203 A A 10^(2 e) 1 4.141 2 A B 10^e 1 1.344 10^(2 e) 1 1.031 B B 1 0.656 10^e 1 0.625 10^e 1 0.016 2^200000000+1 As you can see 5 seconds are spent on splitting the numbers (pre-processing). And each half size multiplication took double of original squaring time because of adding zeros.
Already I've shown here that it is quite possible to improve the speed of some of Mathematica functions by rewriting them.
Anyway to reduce the timing of FastSquare function to less than timing of ^2 ?