Take a Number And Sum Its Digits Raised To The Consecutive Powers And ….¡Eureka!! ( 6 kyu )

문제

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What’s the use of saying “Eureka”? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let’s see some cases:

sumDigPow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sumDigPow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

첫번째와 두번째 인자 사이에 해당 값이 각자릿수의 제곱합과 같은 수를 찾아 리턴하는 문제

풀이

function sumDigPow(a, b) {
  let result = [], arr, sum = 0;
  for ( let i = a; i <= b; i++ ) {
    arr = i.toString().split('').map(Number);
    sum = 0;
    for ( let j = 0; j < arr.length; j++ ) {
      sum += Math.pow(arr[j], j+1);
    }
    if ( i === sum ) {
      result.push(i);
    }
  }
  return result;
}

포문 두개로 구성해서 그냥 노가다 식으로 짰는데, 통과는 되었지만 좋은 코드는 아닌 것 같다.

다른 사람의 풀이

function sumDigPow(a, b) {
  var ans = [];
  while(a <= b){
    if(a.toString().split('').reduce((x,y,i)=>x + +y ** (i + 1),0) == a)
      ans.push(a);
    a++;
  }
  return ans;
}

접근은 같지만 조금더 간결하게 코드를 작성하는 방법

언제봐도 리듀스는 너무 어려움

리듀스 세번째 인자는 인덱스.. 메모..


+ Recent posts