Multiply Two Numbers: I I I I+1
Multiply Two Numbers: I I I I+1
i=0
A
i
10
i+1
= x . (1)
So, the product of the two numbers can be written down in the way we have done it.
Analysis of Time and Space complexity the Algorithm
Algorithm executes one of the for loops n times, and in each iteration it executes another loop,
which in each iteration takes O(1) time. Thereafter, it spends a total of O(m n) time in the for
loop. This takes O(n m) time and O(n + m) space. So overall time complexity of the algorithm
is O(n m) and the overall space complexity is O(n + m).
In the special case, when both the numbers have n digits, the time complexity becomes O(n
2
) and
overall space complexity becomes O(n).
1 Flow Chart
Enter numbers
Multiply last digits
Carry result modulus 10
Do this for all digits of
b and add the result for
each digit of a
1
Data: Input will be two arrays A[0..n 1] and B[0...m1]. However, the algorithm will
use additional arrays temp[0..n] and ans[0....n + m] such that temp will store the
temporary product for the i iteration and L, after the last iteration, will store the
nal product.
Result: The product of the given numbers.
1 var1 n;
2 var2 0;
3 var3 0;
4 var4 0;
5 for j n + m to 0 do
6 ans[j] 0;
7 end
8 for i m1 to 0 do
9 for j 1 to n do
10 temp[n] 0;
11 end
12 for j n 1 to 0 do
13 if ((B[i] A[j]) + var2) 9 then
14 temp[var1] ((B[i] A[j]) + var2);
15 var1 var1 1;
16 else
17 temp[var1] (B[i] A[j] + var2)%10;
18 var2 (B[i] A[j] + var2)/10;
19 var1 var1 1;
20 end
21 end
22 temp[var1] var2;
23 var2 0;
24 var1 n;
25 for j (n + mi) to mi do
26 ans[j] (ans[j] + temp[j + i m] + var4);
27 var4 (ans[j] + temp[j + i m] + var4)%10;
28 end
29 ans[m1 i] var4;
30 var4 0;
31 end
32 This algorithm gives the product whose digits are stored on the array sum.
Algorithm 1: Algorithm for nding the Product of two numbers
2
6
4
2
1 2
4
1
3
6
5
0
2 0 0
2 5 8 3 0
References
[1] Rohit Kumar Jha. Carrying in numbers. 2012.
[2] Rohit Kumar Jha. How to multiply. 2012.
3