## The challenge#

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

## The solution in Kotlin code#

Option 1:

``````package solution

object ASum {

fun findNb(m: Long): Long {
var n: Long = 0
var cubeSize: Long = 0
while (cubeSize < m) {
cubeSize += n * n * n
n++
}
return if (cubeSize == m) n - 1 else -1
}
}
``````

Option 2:

``````package solution

object ASum {

fun findNb(m: Long): Long {
var sum = 0L
return generateSequence(1L) { it + 1 }
.onEach { sum += it*it*it }
.takeWhile { sum <= m }
.lastOrNull { sum == m }
?: -1
}
}
``````

Option 3:

``````package solution
import kotlin.math.pow

object ASum {
fun findNb(m: Long): Long {
var i = 0.0;
var n = 0.0;
while(n < m) {
n += (i).pow(3);
if(n.toLong() == m)
return i.toLong();
i++;
}
return -1;
}
}
``````

## Test cases to validate our solution#

``````package solution

import org.junit.Test
import kotlin.test.assertEquals

class  ASumTest {

private fun testing(n: Long, expected: Long) {
var actual = ASum.findNb(n)
assertEquals(expected, actual)
}
@Test
fun fixedTests() {
testing(56396345062501, -1)
testing(6132680780625, 2225)
testing(28080884739601, -1)

}
}
``````