작성일 :

문제 링크

2501번 - 약수 구하기

설명

이 문제는 정수 NK가 주어졌을 때,
N의 약수들 중에서 K번째로 작은 수를 출력하는 문제입니다.

약수가 K개 미만이면 0을 출력해야 합니다.


접근법

  • 1부터 N까지 순차적으로 탐색하며 N의 약수를 찾습니다.
  • 약수를 찾을 때마다 카운트를 증가시키고, K번째 약수에 도달하면 바로 출력합니다.
  • 반복문을 모두 순회하였는데 K번째 약수가 없다면 0을 출력합니다.

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

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var input = Console.ReadLine()!.Split();
      int n = int.Parse(input[0]);
      int k = int.Parse(input[1]);

      int cnt = 0;
      for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
          cnt++;
          if (cnt == k) {
            Console.WriteLine(i);
            return;
          }
        }
      }

      Console.WriteLine(0);
    }
  }
}



[ 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
#include <bits/stdc++.h>

using namespace std;

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

  int nat, order; cin >> nat >> order;
  int cnt = 0;
  for (int i = 1; i <= nat; i++) {
    if (nat % i == 0) {
      cnt++;
      if (cnt == order) {
        cout << i << "\n";
        return 0;
      }
    }
  }

  cout << "0\n";

  return 0;
}