Sherlock and Squares HackerRank Solution in C, C++, Java, Python

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 .




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


  • 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.

Sample Input


3 9

17 24


Sample Output




Sherlock and Squares HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int t;
    int a,b,sa,sb;
    	scanf("%d %d",&a,&b);
        sa = sqrt(a), sb = sqrt(b);
        if(sa*sa == a)sa--;
        printf("%d\n",sb - sa);
      var testCases = int.Parse(Console.ReadLine());
      for(var i = 0; i < testCases; i++)
        var input = Console.ReadLine().Split();
        var A = int.Parse(input[0]);
        var B = int.Parse(input[1]);
        var sqrA = Math.Ceiling(Math.Sqrt(A));
        var sqrB = Math.Floor(Math.Sqrt(B));
        var squares = 0;
        for(var j = sqrA; j <= sqrB; j++)
          var square = j*j;
          if (square >= A && square <= B)


Attempt Sherlock and Squares HackerRank Challenge 

Link –

Next HackerRank Challenge Solution 

Link –


Leave a Comment