# Sherlock and Squares – HackerRank Solution

In this post, we will solve Sherlock and Squares HackerRank Solution. This problem (Sherlock and Squares) is a part of HackerRank Algorithms series.

Contents

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 = 49

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 <= 109

Sample Input

``````2
3 9
17 24``````

Sample Output

``````2
0``````

Explanation

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.

## Solution – Sherlock and Squares – HackerRank Solution

### C++

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int n,m;
cin>>n;

while (cin>>n>>m)
{
cout<<(int)(sqrt(m)+0.0000001)-(int)(sqrt(n-1)+0.0000001)<<endl;
}
return 0;
}
```

### Python

```#!/bin/python3

import sys
from math import ceil, floor

def squares(a, b):
res = 0
res = floor(b**0.5)+1 - ceil(a**0.5)
return res

if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
a, b = input().strip().split(' ')
a, b = [int(a), int(b)]
result = squares(a, b)
print(result)
```

### Java

```import java.util.Scanner;
class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int h=0;h<t;h++)
{
int m=sc.nextInt();
int n=sc.nextInt();
int count=0;
int sq=(int) Math.sqrt(m);
int a=sq*sq;
if(a<m)
{
sq++;
a=sq*sq;
}
while(a>=m && a<=n)
{
count++;
sq++;
a=sq*sq;

}

System.out.println(count);
}
}
}
```

Note: This problem (Sherlock and Squares) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.