Java

알고리즘. 최대 공약수와 최소 공배수

note994 2024. 8. 8. 10:51
class Solution {
    public int[] solution(int n, int m) {
        int[] answer = new int[2];
        
        // Swap n and m if n is greater than m
        if (n > m) {
            int temp = n;
            n = m;
            m = temp;
        }
        
        // Calculate GCD using Euclidean algorithm
        int gcd = gcd(n, m);
        
        // Calculate LCM using the relation LCM(a, b) = a * b / GCD(a, b)
        int lcm = (n * m) / gcd;
        
        answer[0] = gcd;
        answer[1] = lcm;
        
        return answer;
    }

    // Helper method to calculate GCD
    private int gcd(int a, int b) { //a는 작은값 b는 큰값
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}