Multiply Large Numbers represented as Strings in C++

C++Server Side ProgrammingProgramming

Given two numbers in the string formats. We need to multiply them. The idea to solve the problem is to maintain a previous digit multiplication answer and carry. We can use the previous digits multiplication answer and carry to get the next set digits multiplication.

Let's see an example.

Input

15
2

Output

30

Algorithm

  • Initialise the numbers in string.

  • Initialise a string of length number_one_length + number_two_length.

  • Iterate over the first number from the end.

    • Iterate over the second number from the end.

      • Multiply two digits and add the corresponding previous row digit.

      • Update the previous row digit.

      • Store the carry in the previous index of the result string.

  • Convert the char to digits by adding 0 character to every character in the result.

  • Return the result by ignoring the leading zero.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
string multiplyTwoNumbers(string num1, string num2) {
   if (num1 == "0" || num2 == "0") {
      return "0";
   }
   string product(num1.size() + num2.size(), 0);
   for (int i = num1.size() - 1; i >= 0; i--) {
      for (int j = num2.size() - 1; j >= 0; j--) {
            int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];
            product[i + j + 1] = n % 10;
            product[i + j] += n / 10;
      }
   }
   for (int i = 0; i < product.size(); i++) {
      product[i] += '0';
   }
   if (product[0] == '0') {
      return product.substr(1);
   }
   return product;
}
int main() {
   string num1 = "34";
   string num2 = "57";
   if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {
      cout << "-";
   }
   if(num1.at(0) == '-') {
      num1 = num1.substr(1);
   }
   if(num2.at(0) == '-') {
      num2 = num2.substr(1);
   }
   cout << multiplyTwoNumbers(num1, num2) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

1938
raja
Published on 03-Jul-2021 04:32:29
Advertisements