Divide large number represented as string in C++ Program


In this tutorial, we are going to learn how to divide a large number that is represented as a string.

We have given a large number in string format and a divisor. Our program should find a reminder.

First, we will find a part of the given number that is greater than the dividend. And then we will add the remaining digits one by one to the divisor.

Let's see the steps to solve the problem.

  • Initialize the large number along with a divisor.

  • Iterate over the given number until we extract the part that is greater than the divisor.

  • Now, iterate from where we left in the previous step until the end of the number.

    • Divide the extracted part with a divisor and add it to the result.

    • Update the number with the next digit.

  • Check whether the result is zero or not.

  • And print the result.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
string divideLargeNumber(string number, int divisor) {
   // to store the result
   string result;
   int index = 0;
   // extracting the part that is greater than the given divisor
   int dividend = number[index] - '0';
   while (dividend < divisor) {
      dividend = dividend * 10 + (number[++index] - '0');
   }
   // iterating until all digits participate in the division
   while (number.size() > index) {
      result += (dividend / divisor) + '0';
      // adding the next digit to the dividend
      dividend = (dividend % divisor) * 10 + number[++index] - '0';
   }
   if (result.length() == 0) {
      return "0";
   }
   return result;
}
int main() {
   string large_number = "12345678901234567890";
   int divisor = 75;
   cout << divideLargeNumber(large_number, divisor) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

164609052016460905

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements