Conversation
There was a problem hiding this comment.
Unfortunately, it doesn't work like this due to floating point error: 1/3 can not be precisely represented as a float. Thus Math.pow(x, 1/3), no matter how well it is implemented, will only ever give you an approximation to the correct cube root. Additionally, Math.pow will always approximate the solution (f.E. it may, theoretically, use taylor series for this), so there will be another error margin.
You could (presumably) mitigate this by using Math.round(n**(1/3))**3 == n instead.
Here's a small snippet to verify this:
for (let i = 0; i < 1000; i++) { if (!perfectCube(i*i*i)) console.log(i*i*i) }Even rather small numbers like 64 will be erroneously classified as imperfect cubes.
Oh yes, thank you, I didn't think about this floating point approximation. I've implemented and tested your suggestion, as well as some new test cases for higher numbers that would be wrong with the former implementation. |
Implementation of a perfect cube.