CodeWars 코딩 문제 2021/03/16 - Build a pile of Cubes

이호현·2021년 3월 16일
0

Algorithm

목록 보기
90/138

[문제]

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.

Examples:
findNb(1071225) --> 45

findNb(91716553919377) --> -1

(요약) 1부터 n까지 각 숫자의 3제곱의 합이 주어진 수와 n이 몇일 때 같아지는지 찾아라.
없으면 -1을 return.

[풀이]

function findNb(m) {
  let n = 1;

  while(Math.pow(n * (n + 1) / 2  , 2) <= m) {
    if(Math.pow(n * (n + 1) / 2  , 2) === m) {
      return n
    }
    else {
      n++;
    }
  }

  return -1;
}

1부터 임의의 숫자 n까지 3제곱들의 합을 구하고 비교하고 하려면 반복문을 2중으로 써야될거 같음.

그래서 고등학교 때 배웠나 시그마 공식이 떠올라서 그걸 사용하기로 함.

물론 정확한 식은 생각이 안나서 구글링.

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

0개의 댓글