# Build a pile of Cubes in Kotlin

## 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:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width: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
}
}
```Code language: Kotlin (kotlin)```

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
}
}
```Code language: Kotlin (kotlin)```

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;
}
}
```Code language: Kotlin (kotlin)```

## 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)

}
}
```Code language: Kotlin (kotlin)```
Tags:
Subscribe
Notify of