[백준] 5347번 - LCM [Java][C++]
[백준] 5347번 - LCM [Java][C++]
1. 문제 풀이
각 자연수의 최소공배수를 출력하는 문제로 최대공약수를 구할 수 있는 유클리드 호제법을 활용하면 간단하게 해결할 수 있다. 최소공배수는 두 수의 곱을 최대공약수로 나누면 된다. 최소공배수를 구하는 과정에서 정수 타입의 오버플로우에 주의해야 한다.
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
25
26
27
28
29
30
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 n = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= n; tc++) {
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 long lcm(int a, int b) {
return (long) a / gcd(a, b) * b;
}
}
2. 유클리드 호제법 [C++]
lcm 함수를 활용해서 간단하게 해결했다.
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(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int tc = 1; tc <= n; tc++) {
long long a, b;
cin >> a >> b;
cout << lcm(a, b) << '\n';
}
}
3. 풀이 정보
1. 유클리드 호제법 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 100 ms | 14004 KB | 819 B |
2. 유클리드 호제법 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 0 ms | 2020 KB | 270 B |
This post is licensed under CC BY 4.0 by the author.