Home > Web Front-end > JS Tutorial > Codewars - Build a pile of Cubes

Codewars - Build a pile of Cubes

Patricia Arquette
Release: 2025-01-07 08:32:39
Original
576 people have browsed it

Salutations.

Codewars - Build a pile of Cubes

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);
}
Copy after login

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 ???.

Previous

The above is the detailed content of Codewars - Build a pile of Cubes. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template