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

allnight5·2023년 1월 11일
0

프로그래머스

목록 보기
13/73

두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. 예를 들어 두 수 3, 12의 최대공약수는 3, 최소공배수는 12이므로 solution(3, 12)는 [3, 12]를 반환해야 합니다.
유클리드호제법

파이썬

def solution(n, m):
    answer = []  
    temp1=n
    temp2=m
    #최대공약수 gcd구하는공식 유클리드호제법
    while temp1 != 0:
        t = temp2%temp1
        (temp2,temp1) = (temp1,t) 
    #gcd = temp2
    #최소공배수 공식 gcd = 최대공약수
    #lcm(a,b) = |ab|/gcd(a,b) 
    answer = [temp2 ,n*m//temp2]
    
    return answer 

자바

class Solution {
    public int[] solution(int n, int m) {
        int[] answer = new int[2];
        int temp1 = n;
        int temp2 = m;
        while(temp1>0){
            int temp = temp2%temp1;
            temp2 = temp1;
            temp1 = temp;
            answer[0] = temp2;                
        }
        answer[1] = n*m/answer[0];
        return answer;
    }
}
profile
공부기록하기

0개의 댓글