[BaekJoon] #1934 - 최소공배수 [Java][C++]
[BaekJoon] #1934 - 최소공배수 [Java][C++]
1. 아이디어
각 테스트 케이스마다 두 자연수의 최소공배수를 출력하는 문제로 최대공약수를 구할 수 있는 유클리드 호제법을 활용하면 간단하게 해결할 수 있다. 최소공배수는 두 수의 곱을 최대공약수로 나누면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(T \log M)$ | $O(1)$ |
($T$ = 테스트 케이스 수, $M$ = a, b의 최댓값. Java는 전체 출력을 StringBuilder에 모았다가 출력하므로 공간 $O(T)$)
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
25
26
27
28
29
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));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
sb.append(lcm(a, b)).append("\n");
}
System.out.println(sb);
}
static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
cout << lcm(a, b) << '\n';
}
}
This post is licensed under CC BY 4.0 by the author.