본문 바로가기
알고리즘/Codewars

[Codewars] Playing with digits (6 kyu) / JavaScript

by fluss 2022. 12. 13.

https://www.codewars.com/kata/5552101f47fc5178b1000050

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Some numbers have funny properties. For example:

89 -->  + 9² = 89 * 1

695 --> 6² +  + 5⁴= 1390 = 695 * 2

46288 -->  + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p

  • we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k * n.

In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

 

Note: n and p will always be given as strictly positive integers.

digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
 
 

설명:

어떤 숫자들은 재미있는 속성을 가지고 있습니다. 예를 들어:

89 -->  + 9² = 89 * 1

695 --> 6² +  + 5⁴= 1390 = 695 * 2

46288 -->  + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

 

abcd...(a, b, c, d... 는 숫자)로 쓰인 양의 정수 n과 양의 정수 p가 주어집니다.

  •  n의 자릿수를 p의 연속적인 거듭 제곱을 한 합이 k * n과 같은 k가 존재한다면 양의 정수 k를 찾고 싶습니다.

 

다시 말해:

 (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k와 같은 정수 k가 있나요?

그렇다면 k를 반환하고 그렇지 않다면 -1을 반환합니다.

 

 

참고: n과 p는 오로지 엄밀하게 양의 정수로 주어집니다.

digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
 

풀이

n을 한 자리씩 자르고 자리마다 p를 하나씩 늘려가면서 거듭제곱을 해주었다. 그리고 그 합을 n으로 나누었을 때 나머지가 0이라면 그 나눈 값을 그렇지 않다면 -1을 반환했다.

 

코드

function digPow(n, p){
  digits = String(n).split('').map(el => parseInt(el));
  let sum = 0;
  for(let i = 0; i < digits.length; i++){
    sum += digits[i] ** p;
    p += 1;
  }
  if(sum % n !== 0) return -1;
  return sum / n;
}

댓글