Sherlock and Squares Solution in Javascript
by Travis Scott Lee
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. 1,4,9,16,25.
Example
a = 24
b = 29
There are three square integers in the range: 25, 36 and 49. Return 3.
Function Description
Complete the squares function in the editor below. It should return an integer representing the number of square integers in the inclusive range from a to b.
squares has the following parameter(s):
- int a: the lower range boundary
- int b: the upper range boundary
Returns
- int: the number of square integers in the range
Input Format
The first line contains q, the number of test cases.
Each of the next q lines contains two space-separated integers, a and b, the starting and ending integers in the ranges.
Constraints
1 ≤ q ≤ 100
1 ≤ a ≤ b ≤ 10⁹
Solution
For this algo, we round up the product of a and round down the product of b is because to optimize the run time of the algo. If we scanning thousands of number between one to ten thousand, the algo is going to take a while to check if it is a square root or not. Then, we set a for
loop to check the range between the rounded square roots of a and b. For even integer we pass in the loop the counter will go up. Realizing now, the if
statement within that for
loop is redundant.