problem
For the multiplication of two large integers, for example, the number of two digits is 1024x768, and the C language cannot represent such a large number. But we can use the Division method to find their product.
Solve
Without losing its generality, two numbers a and B are n bits, and n is the power of 2. If this condition is not met, you can make them satisfy by filling the 0 operation.
A:
B:
Then a*b can be written as:
A*b = (A1*10^N/2 + A2) * (B1*10^N/2 + b2)
= A1*b1*10^n + (A1*B2+A2*B1) *10^N/2 + a2*b2
If you only switch to this point, then the time complexity of the algorithm is still very high
The recursive relationship is: T (n) = 4T (N/2) + O (n), because after decomposition, there are 4 different multiplication operations
After calculation, the time complexity is O (n^2)
We can also continue to optimize. A1*b1*10^n + (A1*B2+A2*B1) *10^N/2 + a2*b2, in this equation, A1*B2+A2*B1 can be expressed using A1*B1 and A2*B2.
A1*B2+A2*B1 = (A1-A2) * (B2-B1) + A1*B1 + a2*b2
In this way, a*b can be expressed as:
A1*b1*10^n + ((A1-A2) * (B2-B1) + a1*b1 + a2*b2) *10^N/2 + a2*b2
There are 3 different multiplication in this one. The time complexity of the add and subtract operation is O (n)
The recursive relationship is: T (n) = 3T (N/2) + O (n)
Time complexity: O (n^log3) = O (n^1.59)
Large integer Multiplication