PAT B Zhenti 1007.A divided by B
Title Description
This problem requires calculation of A / B, where A is not more than 1000 bit positive integer, B is a positive integer. You need to output quotient Q and a remainder R, such that A = B * Q + R established.
Input Format
1 is given input line are sequentially A and B, separated by an intermediate space.
Output Format
Q and R are sequentially output in a line, separated by an intermediate space.
SAMPLE INPUT
123456789050987654321 7
Sample Output
17636684150141093474 3
Topic ideas
Bit division is employed, the remainder calculation of the carry way.
Example:
367/2
first calculates 3/2 = 1 I 1
recalculation dividend remainder number of carry over plus calculation
is (6 + 1 * 10) / 2 = 8 I 0
recalculation (7 + 0 * 10) / 3 I 2 = 1
the final addition result is out of the sequence of formula 183 thanks to a
remainder of 1 is the last remainder
final output is: 1831
Problem-solving code is as follows:
#include<iostream>
using namespace std;
const int N = 1e3 + 10;
int main()
{
char a[N];
int c[N];
int b, d = 0, i = 0;
scanf("%s%d", a, &b);
do {
c[i] = ((a[i] - 48)+d*10) / b;
d = ((a[i] - 48)+d*10) % b;
i++;
} while (a[i] >= '0'&&a[i] <= '9');
if (c[0] != 0)
for (int j = 0; j < i; j++)
{
printf("%d", c[j]);
}
else
for (int j = 1; j < i; j++)
{
printf("%d", c[j]);
}
printf(" %d", d);
return 0;
}