Sunday, June 7, 2015

Multiplication of two large numbers by storing intermediate values in C++

If we are asked to multiply two numbers of hundred digits each, how we are going to solve this problem?

One approach to solve this kind of problems is to store intermediate values and compute the final result using this. The intermediate values will not be as large as the number with hundred digits, therefore the computation becomes easy.
The idea of this approach is taken from the basic multiplication that we were taught during school days. This naive approach i.e. write one number above the other, then do long multiplication helps us to know the intermediate values which is used to compute the final result.

Let's go back to naive method where we used to do multiplication in this way


    9999
x      19

     -----
                                  89991                  // array1
                             + 99990                 //array2
 ---------
 189981



If we multiply the first two digits of this example i.e 9*9 the intermediate value is 81 where 8 is carry and 1 is stored in a temporary array. In the next step we multiply next digit of multiplicand i.e 9*9 Similarly we repeat this process and store each intermediate digit at each index in an array. Here we can use two arrays for storing the entire intermediate values. Adding both arrays will give the result.


Here is an example program for multiplying two large numbers.



#include <string>
#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
void product(string a, string b) {
vector<int> result(a.size() + b.size(), 0);
for( int i = a.size() - 1; i >= 0; i-- ){
for( int j = b.size() - 1; j >= 0; j-- ){
result[ i + j + 1 ] += ( b[ j ] - '0') * ( a[ i ] - '0' ); //single array to store intermediate values
}
}
for( int i = a.size() + b.size(); i >= 0; i-- ){
if( result[ i ] >= 10 ){
result[ i - 1 ] +=result[ i ] / 10;
result[ i ] %= 10;
}
}
cout << a << " * " << b << " = ";
for( int i = 0; i < a.size() + b.size(); i++ ){
cout << result[ i ];
}
cout << endl;
}
int main( void ){
string str1, str2 ;
str1 = "99999999999999999999";
str2 = "9985995948565498566";
product( str1, str2 );
return 0;
}











2 comments:

  1. nice code, however just try 20*20 and see the result

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete