CodeWars 코딩 문제 2021/01/20 - SPrimes in numbers

이호현·2021년 1월 20일
0

Algorithm

목록 보기
58/138

[문제]

Given a positive number n > 1 find the prime factor decomposition of n. The result will be a string with the following form :

"(p1**n1)(p2**n2)...(pk**nk)"

where a ** b means a to the power of b

with the p(i) in increasing order and n(i) empty if n(i) is 1.

Example: n = 86240 should return "(2**5)(5)(7**2)(11)"

(요약) 주어진 숫자를 소인수분해 한 다음에 소수들의 n제곱 형태로 표현해라.

[풀이]

function primeFactors(n){
  const primes = {};
  let currentPrime = 2;
  let answer = '';

  while(n > 1) {
    if(!(n % currentPrime)) {
      primes[currentPrime] ? primes[currentPrime] += 1 : primes[currentPrime] = 1;
      n /= currentPrime;
    }
    else {
      currentPrime++;
      for(let i = 2; i <= Math.sqrt(currentPrime); i++) {
        if(!(currentPrime % i)) {
          break;
        }
      }
    }
  }

  for(let key in primes) {
    answer += `(${key}${primes[key] === 1 ? '' : '**' + primes[key]})`;
  }

  return answer;
}

n을 가장 작은 소수인 2부터 나누기 시작.
나눠지면 primeskey를 소수로 갖는 요소에 개수 추가하고,
아니면 다음 소수를 찾음.
n이 1이 될 때까지 반복한 후, for in문을 이용해 문자열로 만들어주고 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글