My intent is not to provide an answer per se, rather it’s to provide insight into the way I think and to foster discussion. Copy & paste at your own risk.
This the 2nd of 3 tests that I recently took in applying for a developer position. Due to copyright restrictions I cannot post the problem here verbatim. I’ve substituted certain values and names. I can give you the gist (both :) here:
- the input value X is within the range -2147483648 to 2147483647
- the input value Y is within the range -2147483648 to 2147483647
- X <= Y
Write a function
function solveIt(X, Y);
that will return the number of whole cubes within the range of integers X and Y, including X and Y if applicable.
Sometimes the simplest solution is staring you in the face but like many developer issues of the Computer Science flavor, we developers can’t seem to see the forest for the trees. I knew this was one of those problems. Rather than attack this code-first, I decided to detach myself from my developer role and approach this as a word problem given to a high-school student.
The easiest way to find the nearest whole cube’s root is to just try to find the cube root of a number. Since we’re working within a range we can assume the following:
- negative numbers will have a single negative cube root (rather than try to deal with NaN results, imaginary numbers or other mathematical anomalies, keep in mind Math.pow(-n, 1/3) returns NaN)
- if the cube root of a number is an integer, then the number is a whole cube otherwise
- for the lower range’s number we need to round the cube root up (Math.ceil)
- for the upper range’s number we need to round the cube root down (Math.floor)
- negative numbers can be treated as positive values given the first assumption (which I make use of by recursively calling my solveIt function)
core solution & float fix
w/ quint tests