[BaekJoon] 2501번 - 약수 구하기 [Java][C++]
[BaekJoon] 2501번 - 약수 구하기 [Java][C++]
1. 문제 풀이
$N$ 의 $K$ 번째 약수가 존재하면 해당 수를, 존재하지 않으면 $0$ 을 출력하는 문제다. $1$ 부터 $N$ 까지 $N$ 을 나누어서 나머지가 $0$ 이 되면 약수이며 이 개수를 세다가 $K$ 가 되면 해당 수를, 되지 않으면 $0$ 을 출력하도록 구현했다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int order = 0;
for (int i = 1; i <= N; i++) {
if (N % i == 0) order++;
if (order == K) {
System.out.println(i);
return;
}
}
System.out.println(0);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
int order = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) order++;
if (order == k) {
cout << i;
return 0;
}
}
cout << 0;
}
This post is licensed under CC BY 4.0 by the author.