Post

[백준] 2609번 - 최대공약수와 최소공배수 [Java][C++]

[백준] 2609번 - 최대공약수와 최소공배수 [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
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(gcd(A, B));
        System.out.println(lcm(A, B));
    }

    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;
    }
}

2. 유클리드 호제법 [C++]

gcd, lcm 함수를 활용해 간단하게 해결했다.

1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b;
    cin >> a >> b;
    cout << gcd(a, b) << '\n';
    cout << lcm(a, b) << '\n';
}

3. 풀이 정보

1. 유클리드 호제법 [Java]

언어시간메모리코드 길이
Java 11108 ms14220 KB636 B

2. 유클리드 호제법 [C++]

언어시간메모리코드 길이
C++ 170 ms2020 KB213 B

This post is licensed under CC BY 4.0 by the author.