[BaekJoon] 13241번 - 최소공배수 [Java][C++]
[BaekJoon] 13241번 - 최소공배수 [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
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 A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
System.out.println(lcm(A, B));
}
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++]
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long a, b;
cin >> a >> b;
cout << lcm(a, b);
}
This post is licensed under CC BY 4.0 by the author.