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
부터 나누기 시작.
나눠지면primes
에key
를 소수로 갖는 요소에 개수 추가하고,
아니면 다음 소수를 찾음.
n
이 1이 될 때까지 반복한 후,for in
문을 이용해 문자열로 만들어주고return
.