Build a pile of Cubes ( 6 kyu )
문제
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부터 결과값까지 세제곱의 합이 인자값이 되는 경우를 찾아 리턴, 없다면 -1 리턴
풀이
function findNb(m) {
let sum = 0, i = 1;
while ( sum < m ) {
sum += Math.pow(i, 3);
if ( sum === m ) {
return i
}
i++
}
return -1;
}
sum에 1부터 세제곱의 합을 담고, sum이 m 보다 커질때까지 while문을 돌려 만약 m과 같은 값이 있다면 i를 리턴, 아니라면 -1을 리턴
다른 사람의 풀이
function findNb(m) {
var n = 0
while (m > 0) m -= ++n**3
return m ? -1 : n
}
똑같지만 간결해보임.