Sherlock and Squares
Watson likes to challenge Sherlock’s math ability. He will provide a starting and ending value that describe a range of integers, inclusive of the endpoints. Sherlock must determine the number of square integers within that range. Note: A square integer is an integer which is the square of an integer, e.g. Example:-
There are two square integers in the range: 4 and 9 which return 2.
An interesting hackerrank problem which had many solution but we needed an optimized one.For solving this problem we will need to import math library to use function like floor and ceil. The floor function will reduce the number i.e if 5.9 is passed to the floor function it will convert it to 5 where the ceil function will upgrade the number value to 6.NOw lets move towards the problem we can use the option of iterating through the range and taking square root of each number and then taking modulo of the square root and the number and increment the counter if the modolo is 0 but this will not work for bigger number.so if we find the square root of start and end number , that will give you a start and end of this range of integers which provide the squared values in your required range.
For example ,if range is given of 24 to 49,the square root of 24 is between 4–5 and that of 49 is 7. So in between 4 to 7 we have 5,6,7 whose perfect square falls in range 24 to 49 i. e 3 numbers. This is clearly a lot faster than checking each one or trying to create a database of all primes for lookup, or any other method. The code is pretty much simple, we just trying to floor value of square root of “b” and ceil the square root value of “a” and substract them and add 1 to it as the range is inclusive and return the
def squares(a, b):
“You simply have to put one foot in front of the other and keep going”.Been away from this challenge but right on track.Keep on moving and keep hustling…(cheer:-PN)