Sherlock and Squares

June 28, 2019  

Watson likes to challenge Sherlock’s math ability. He will provide a starting and ending value describing a range of integers. Sherlock must determine the number of square integers within that range, inclusive of the endpoints.

Note: A square integer is an integer which is the square of an integer, e.g. 1, 4, 9, 16, 25

For example, the range is a = 24, b = 49, inclusive. There are three square integers in the range: 25, 36, 49.

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):

a: an integer, the lower range boundary
b: an integer, the uppere range boundary

Input Format

The first line contains q, the number of test cases.

Each of the next q lines contains two space-separated integers denoting a and b, the starting and ending integers in the ranges.



Output Format

For each test case, print the number of square integers in the range on a new line.

Sample Input

 3 9
 17 24

Sample Output



Test Case #00: In range [3, 9], 4 and 9 are the two square integers.

Test Case #01: In range [17, 24], there are no square integers.


import math

def squares_between(a, b):
    count = math.floor(math.sqrt(b)) - math.floor(math.sqrt(a - 1))
    return count

if __name__ == '__main__':
    test_count = int(input())

    for _ in range(test_count):
        a, b = tuple(int(pair) for pair in input().split())
        print(squares_between(a, b))

Let’s connect in Linkedin and Twitter !

Buy me a beer Buy me a beer