C++ Program for quotient and remainder of big number

C++Server Side ProgrammingProgramming

Given a sting of a big number say num and another big number say m; the task is to print the quotient using divide operation and the remainder of the big number using modulus.

The output should be Remainder = xxx; Quotient = yyy

Let’s assume we have an input num = string num = "14598499948265358486" and other input m = 487 so the remainder is 430 and quotient is 29976385930729688.

Example

Input: num = “214755974562154868”
   m = 17
Output: Remainder = 15
   quotient = 12632704386009109
Input: num =“214”
   m = 5
Output: Remainder = 4
   Quotient = 42

Approach we will be using to solve the given problem

  • Initially set mod to 0.
  • Starting from the right we have to find it mod using: mod = (mod * 10 + digit) % m.
  • Finding the quotient by quo[i] = mod/m, where i is the position number of quotient.

Algorithm

Start
   Step 1 -> Declare long long ll
   Step 2 -> In function void quotientremainder(string num, ll m)
      Declare a vector<int> vec
      Set ll mod = 0
      Loop For i = 0 and i < num.size() and i++
         Set digit = num[i] - '0'
         Set mod = mod * 10 + digit
         Set quo = mod / m
         Call vec.push_back(quo)
         Set mod = mod % m
      End loop
      Print remainder value which is in mod
      Set zeroflag = 0
      Loop For i = 0 and i < vec.size() and i++
         If vec[i] == 0 && zeroflag == 0 then,
            Continue
         End If
         zeroflag = 1
         print the value of vec[i]
      End For
      Return
   Step 3 -> In function int main()
      Declare and assign num = "14598499948265358486"
      Declare and assign ll m = 487
      Call function quotientremainder(num, m)
Stop

Example

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Function to calculate the modulus
void quotientremainder(string num, ll m) {
   // Store the modulus of big number
   vector<int> vec;
   ll mod = 0;
   // Do step by step division
   for (int i = 0; i < num.size(); i++) {
      int digit = num[i] - '0';
      // Update modulo by concatenating
      // current digit.
      mod = mod * 10 + digit;
      // Update quotient
      int quo = mod / m;
      vec.push_back(quo);
      // Update mod for next iteration.
      mod = mod % m;
   }
   cout << "\nRemainder : " << mod << "\n";
   cout << "Quotient : ";
   // Flag used to remove starting zeros
   bool zeroflag = 0;
   for (int i = 0; i < vec.size(); i++) {
      if (vec[i] == 0 && zeroflag == 0)
         continue;
      zeroflag = 1;
      cout << vec[i];
   }
   return;
}
// main block
int main() {
   string num = "14598499948265358486";
   ll m = 487;
   quotientremainder(num, m);
   return 0;
}

Output

Remainder : 430
Quotient : 29976385930729688
raja
Published on 20-Nov-2019 12:14:21
Advertisements