23
Jan
2020

Hackerrank Sherlock and Squares (Java)

Java :

static int squares(int a, int b) {
        int noOfSquareInts = 0, squareOfA = 0, squareOfB = 0;
        squareOfA = (int)Math.ceil(Math.sqrt(a));
        squareOfB = (int)Math.floor(Math.sqrt(b));

        noOfSquareInts = squareOfB - squareOfA + 1;

        if(noOfSquareInts < 0){
            noOfSquareInts = 0;
        }

        return noOfSquareInts;

    }

Explanation:

This is a fun question. At first sight, the idea to answer this would be to take the range of numbers from a to b, and run a for loop to check every number in the range. It works for small amount of numbers, but for bigger amount of numbers (like 100 numbers), the loop will cause the dreaded “Terminated due to Timeout” error.

When we see that error, we know we need to remove the loop. To do that, we find the square of the lower range number a, ceil the number and convert it to an integer from a double. Why ceil? Take an example 5, for the lower range. √5 is 2.2360679….., and when using ceil, the number is rounded up to 3. Since the range’s lowest number is 5, the previous perfect square is 4, so squareOfB cannot possible be 2 or lower.

Next, we take the floor of the square of the higher range number b, and convert it to an integer from a double. Why floor? Take an example 19. √19 is 4.35889….. We round it down to 4, since if the range highest’s number is 19, the last perfect square is 16, so squareOfB cannot possible be higher than 4.

After getting both squareOfA and squareOfB, we get noOfSquareInts by subtracting squareOfB from squareOfA + 1. Why + 1? This is to add back the first number omitted in the calculations due to rounding.

The last if loop is just to check if there is any calculation that turns our to be smaller than 0, if yes, assign the number to 0. This technically should not happen, but it’s just for precaution.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *