Java

프로그래머스: 최대공약수와 최소공배수

Daeryuk Kim 2024. 1. 21. 18:39
class Solution {
    public int[] solution(int n, int m) {
        int[] answer = new int[2];
        int big;
        /*
        int GCD; // Greatest Common Divisor
        int LCM; // Least Common Multiple
        */
        if (n > m) {
            big = n;
        } else {
            big = m;
        }
        
        for (int x=1; x<=big; x++) {
            if (n % x == 0 && m % x == 0) {
                answer[0] = x; // 최대공약수
            }
        }
        
        answer[1] = answer[0] * n/answer[0] * m/answer[0]; // 최소공배수
        
        
        return answer;
    }
    public static void main(String[] args) {
        int n = 3;
        int m = 12;

        Solution sol = new Solution();
        int[] result = sol.solution(n,m);
        
        
        System.out.println(result[0]+" "+result[1]);

        
    }
}

밑은 재귀함수의 코드다.

class Solution{
    public int[] gcdlcm(int a, int b) {
        int[] answer = new int[2];

        answer[0] = gcd(a,b);
        answer[1] = (a*b)/answer[0];
        return answer;
    }

    public int gcd(int p, int q) {
        if (q == 0) return p;
        return gcd(q, p%q);
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] result = sol.gcdlcm(12, 18);

        for (int i : result){
            System.out.print(i + " ");
        }
    }
}

아래도 굉장히 심플한 코드다.

class Solution {
    public int[] solution(int n, int m) {
        int[] answer = new int[2];
        for (int i = 1; i < n + m; i++) {
            if (n % i == 0 && m % i == 0) {
                answer[0] = i;
                answer[1] = n * m / answer[0];
            }
        }
        return answer;
    }
    public static void main(String[] args) {
        int n = 3;
        int m = 12;

        Solution sol = new Solution();
        int[] result = sol.solution(n,m);
        
        
        System.out.println(result[0]+" "+result[1]);

        
    }
}