[BaekJoon] #2501 - 약수 구하기 [Java][C++]
[BaekJoon] #2501 - 약수 구하기 [Java][C++]
1. 아이디어
$N$의 $K$번째 약수가 존재하면 해당 수를, 존재하지 않으면 0을 출력하는 문제다. 1부터 $N$까지 $N$을 나누어서 나머지가 0이 되면 약수이며 이 개수를 세다가 $K$가 되면 해당 수를, 되지 않으면 0을 출력하도록 구현했다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][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
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);
}
}
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(0);
cin.tie(0);
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.