작성일 :

문제 링크

14563번 - 완전수

설명

각 수의 진약수 합을 계산해 완전수, 부족수, 과잉수를 판별하는 문제입니다.


접근법

진약수는 자기 자신을 제외한 약수이므로, 1부터 시작해서 √N까지 나누어 떨어지는 약수를 짝으로 더합니다.

N이 1이면 진약수 합은 0입니다.

합이 N과 같으면 Perfect, 작으면 Deficient, 크면 Abundant를 출력합니다.


Code

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
using System;
using System.Text;

class Program {
  static void Main() {
    var input = Console.In.ReadToEnd();
    var parts = input.Split(new[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length == 0) return;
    var idx = 0;
    var t = int.Parse(parts[idx++]);

    var sb = new StringBuilder();
    for (var tc = 0; tc < t; tc++) {
      var n = int.Parse(parts[idx++]);
      var sum = 0;
      if (n > 1) {
        sum = 1;
        var limit = (int)Math.Sqrt(n);
        for (var d = 2; d <= limit; d++) {
          if (n % d != 0) continue;
          var other = n / d;
          sum += d;
          if (other != d) sum += other;
        }
      }

      if (sum == n) sb.AppendLine("Perfect");
      else if (sum < n) sb.AppendLine("Deficient");
      else sb.AppendLine("Abundant");
    }

    Console.Write(sb.ToString());
  }
}

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
#include <bits/stdc++.h>
using namespace std;

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

  int t;
  if (!(cin >> t)) return 0;
  while (t--) {
    int n; cin >> n;
    int sum = 0;
    if (n > 1) {
      sum = 1;
      int limit = (int)sqrt(n);
      for (int d = 2; d <= limit; d++) {
        if (n % d != 0) continue;
        int other = n / d;
        sum += d;
        if (other != d) sum += other;
      }
    }

    if (sum == n) cout << "Perfect\n";
    else if (sum < n) cout << "Deficient\n";
    else cout << "Abundant\n";
  }

  return 0;
}