[Codility] Euclidean algorithms

minnsane·2020년 9월 18일
0

Algorithms

목록 보기
7/8

두 수의 최대 공배수를 찾는 유클리디안 알고리즘.

const gcd = (a, b) => {
  let temp;
  while(b!==0){
    temp = b;
    b = a%b;
    a = temp;
  }
  return a;
}

문제

두 수 A, B의 각 인수들 중 소수가 서로 겹치는지 확인해야 하는 문제

코드

const solution = (A, B) => {
  let Z = A.length;
  let answer =0;
  for(let i=0; i<Z; i++){
      let gcd = getGcd(A[i], B[i]);
      let [m, n] = [0, 0];

      while(m!==1){
        m = getGcd(A[i], gcd);
        A[i] = A[i]/m;
      }

      while(n!==1){
        n = getGcd(B[i], gcd);
        B[i] = B[i]/n;
      }

      if(A[i]===1 && B[i]===1) answer++;
  }
  return answer;
}

const getGcd = (a, b) => {
  let temp;
  while(b>0){
    temp = b;
    b = a%b;
    a = temp;
  }
  return a;
}
  • 서로 최대공배수를 구하고 나누는것까지 생각을 했는데 왜 m, n이 1이 나올때까지 나눠야 하는지는 잘 모르겠다 ㅠㅠㅠㅠ 어렵다...
profile
Knope's not-so-secret binder

0개의 댓글