Salutations.
I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.
The next one is tricky for us, people who struggle with math. It's a nice challenge though. Essentially, it boils down to figuring out the sum of "n" cubes. Then there's some black magic (a.k.a: algebra) et voilà! Solved.
Sum of cubes explained with proof.
Full solution:
function findNb(m) {
// sum of n cubes = ( n^2 * (n+1)^2 ) / 4
let number = m * 4;
number = number ** (1/2);
let numberAux = number ** (1/2);
let floor = Math.floor(numberAux);
let ceiling = (Number.isInteger(numberAux)) ? floor + 1 : Math.ceil(numberAux);
if ( floor * ceiling == number ){
return floor;
}
return (-1);
}
Why do we compute floor
and ceiling
? Because if the argument m
does indeed represent a sum of "n" cubes, then numberAux
is PARTLY the number we are looking for. We just need the integer part. Which is "n". And it's also floor
.
If 'm' does not represent a sum of cubes, then the function returns -1
. No big deal.
It works. I don't know if me-in-6-months will understand anything though.
Take care. Drink water 💧💧💧.
Top comments (0)