작성일 :

문제 링크

6974번 - Long Division

설명

큰 정수 두 개가 주어질 때, 나눗셈의 몫과 나머지를 출력하는 문제입니다.


접근법

한 자리씩 내려오며 나머지를 갱신하는 긴 나눗셈을 구현합니다. 매 단계에서 현재 나머지로 만들 수 있는 최대 한 자리 몫을 찾습니다.

이후 최종 몫과 나머지를 출력하고, 테스트케이스 사이에는 빈 줄을 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Numerics;

class Program {
  static void Main() {
    var t = int.Parse(Console.ReadLine()!);
    for (var tc = 0; tc < t; tc++) {
      var a = BigInteger.Parse(Console.ReadLine()!);
      var b = BigInteger.Parse(Console.ReadLine()!);

      BigInteger rem;
      var q = BigInteger.DivRem(a, b, out rem);

      Console.WriteLine(q);
      Console.WriteLine(rem);
      if (tc + 1 < t) Console.WriteLine();
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std;

string strip(const string& s) {
  int i = 0;
  while (i < (int)s.size() && s[i] == '0') i++;
  if (i == (int)s.size()) return "0";
  return s.substr(i);
}

int cmp(const string& a, const string& b) {
  if (a.size() != b.size()) return a.size() < b.size() ? -1 : 1;
  if (a == b) return 0;
  return a < b ? -1 : 1;
}

string sub(const string& a, const string& b) {
  string res;
  int i = (int)a.size() - 1;
  int j = (int)b.size() - 1;
  int carry = 0;
  while (i >= 0) {
    int x = a[i] - '0' - carry;
    int y = (j >= 0) ? b[j] - '0' : 0;
    if (x < y) {
      x += 10;
      carry = 1;
    } else carry = 0;
    res.push_back(char('0' + (x - y)));
    i--; j--;
  }
  while (res.size() > 1 && res.back() == '0') res.pop_back();
  reverse(res.begin(), res.end());
  return strip(res);
}

string mulDigit(const string& a, int d) {
  if (d == 0) return "0";
  string res;
  int carry = 0;
  for (int i = (int)a.size() - 1; i >= 0; i--) {
    int val = (a[i] - '0') * d + carry;
    res.push_back(char('0' + (val % 10)));
    carry = val / 10;
  }
  while (carry > 0) {
    res.push_back(char('0' + (carry % 10)));
    carry /= 10;
  }
  reverse(res.begin(), res.end());
  return strip(res);
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t; cin >> t;
  for (int tc = 0; tc < t; tc++) {
    string a, b; cin >> a >> b;

    string rem = "0";
    string quot;
    for (char ch : a) {
      if (rem == "0") rem = string(1, ch);
      else rem.push_back(ch);
      rem = strip(rem);

      int q = 0;
      for (int d = 9; d >= 0; d--) {
        string prod = mulDigit(b, d);
        if (cmp(prod, rem) <= 0) {
          q = d;
          rem = sub(rem, prod);
          break;
        }
      }
      quot.push_back(char('0' + q));
    }

    quot = strip(quot);
    rem = strip(rem);

    cout << quot << "\n";
    cout << rem << "\n";
    if (tc + 1 < t) cout << "\n";
  }

  return 0;
}