티스토리 뷰

코딩테스트 연습 - 최대공약수와 최소공배수 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 최대공약수와 최소공배수

두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. 예를 들어 두 수 3, 12의

programmers.co.kr

 

 

 

 

 


나의 코드

const greatestCommonFactors = (n,m) => {
  let commonFactorsArr = [];
  
  let countN = 1;
  let originalN = n;
  let smallerNum = n >= m? m : n;
  while(smallerNum > 0){
    if(n % smallerNum === 0 && m % smallerNum === 0){ 
      break;
    }
    smallerNum--;
  } 
  
  return smallerNum;
}

const leastCommonMultiples = (n,m) => {
  const num =  greatestCommonFactors(n, m);
  
  return num * (n/num) * (m/num); 
}

const solution = (n, m) => {
    let answer = [greatestCommonFactors(n,m),leastCommonMultiples(n,m)];
    return answer;
}

 

smallerNum-- 때문에 조금 지연이 된다

 


나의 코드 2

const greatestCommonFactors = (n,m) => { 
  let smallerNum = n >= m? m : n;
  let biggerNum = n <= m? m : n;
    let r = 0;
  while(biggerNum % smallerNum !== 0){
      r = biggerNum % smallerNum;
    biggerNum = smallerNum;
      smallerNum = r; 
  } 
  
  return smallerNum;
}

const leastCommonMultiples = (n,m) => {
  const num =  greatestCommonFactors(n, m);
  
  return num * (n/num) * (m/num); 
}

const solution = (n, m) => {
    let answer = [greatestCommonFactors(n,m),leastCommonMultiples(n,m)];
    return answer;
}

 

유클리드를 쓰면 훨씬 빨라진다

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함