In: Computer Science
string string_long_division (string dividend, string
divisor)
{
string ans;
//code in here
return ans;
}
Create a function that takes in 2 strings called
dividend (is a string because this could be greater than
the size of an int) and divisor (is a string
because this could be greater than the size of an int) and
performs long division on them and returns the result as a
string.
It would be preferred if the code was written in c++.
THIS CODE SHOULD WORK IN CASES WHERE THE DIVISOR IS ALSO
GREATER THAN THE SIZE OF ANY VARIATION OF AN INT.
For example: dividend = "10000000000000000000000" and
divisor = "1000000000000000000000" should be able to work in the
code.
Thanks!
Hi friend please find below code and execute it in your C++ editor. This will definitely work as per your wish. If don't please feel free to write it here . I will help you out. For your reference I have attached snapshot of C++ editor Thank you.
Q 1 solution
// C++ program to find quotient and remainder
// when a number is divided by large number
// represented as string.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Function to calculate the modulus
void modBigNumber(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;
}
// Driver Code
int main()
{
string num = "10000000000000000000000";
ll m = 1000000000000000000000;
modBigNumber(num, m);
return 0;
}