[백준_2609] 최대공약수와 최소공배수 - JAVA

jm_25·2021년 11월 21일
0

알고리즘

목록 보기
12/40

문제 출처

https://www.acmicpc.net/problem/2609

풀이

  • 최대공약수 / 최소공배수를 구하는 문제는 유클리드호제법을 이용하면 된다.
    (while 문 사용으로 인하여 시간 복잡도는 O(N)

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
        int a = Integer.parseInt(stringTokenizer.nextToken());
        int b = Integer.parseInt(stringTokenizer.nextToken());
        System.out.println(gcd(a, b));
        System.out.println(lcd(a, b));
    }

    private static int lcd(int a, int b) {
        return a * b / gcd(a, b);
    }

    private static int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
}

채점 결과

profile
매일 매일 한 개씩

0개의 댓글