Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Sherlock and Squares Solution

Yashwant Parihar, April 16, 2023April 16, 2023

In this post, we will solve HackerRank Sherlock and Squares Problem Solution. 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.

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.

HackerRank Sherlock and Squares Problem Solution
HackerRank Sherlock and Squares Problem Solution

Sherlock and Squares C Solution

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

int main() {

    int t = 0, tc = -1;
    char tmp[23];
    char cstr[101][23] = {{0}};

    /* Get stdin */
    while (t != tc) {
        memset(tmp, 0, sizeof(tmp));
        fgets(tmp, sizeof(tmp), stdin);
        if (tc == -1) {
            tc = atoi(tmp);
        } else {
            if (tmp[strlen(tmp)-1] == '\n') { tmp[strlen(tmp)-1] = '\0'; }
            strcpy(cstr[t], tmp);
            t++;
        }
    }
    char *tok;
    int a = 0, b = 0, c = 0;
    for (t = 0; t < tc; t++) {
        tok = strtok(cstr[t], " ");
        a = atoi(tok);
        tok = strtok(NULL, " ");
        b = atoi(tok);
        if (sqrt(a) != (int)sqrt(a)) { a = (int)(pow(((int)sqrt(a))+1, 2)); }
        while (a <= b) {
            c++;
            a = (int)(pow(((int)sqrt(a))+1, 2));
        }
        printf("%d\n", c);
        a = 0; b = 0; c = 0;
    }
     return EXIT_SUCCESS;
}

Sherlock and Squares C++ Solution

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


int main() {
	std::vector<unsigned int> squares;
	for (int i = 1; i < 31655; ++i) {
		squares.push_back(i*i);
	}

	int n;
	cin >> n;

	for (int i = 0; i < n; ++i) {
		unsigned int a, b, c = 0;
		cin >> a >> b;

		auto lower = std::lower_bound(squares.begin(), squares.end(), a);
		auto upper = std::upper_bound(squares.begin(), squares.end(), b);

		cout << upper - lower << endl;
	}

	return 0;
}

Sherlock and Squares C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    

    
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int T=int.Parse(Console.ReadLine());
        for(int i =1;i<=T;i++)
            {
            String inp=Console.ReadLine();
            long []arr=Array.ConvertAll(inp.Split(null),s=>(long.Parse(s)));
            long  first,last ;
            first=(long)Math.Sqrt(arr[0]);
            last=(long)Math.Sqrt(arr[1]);
            if(first*first!=arr[0])
                {
                first=first+1;
            }
            
            Console.WriteLine(last-first+1);
        }
    }
}

Sherlock and Squares Java Solution

import java.util.*;
public class Sherlock_and_Squares {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testCase = sc.nextInt();
        while(testCase-->0){
            int start =sc.nextInt();
            int end =sc.nextInt();
            int count=0;
            int square_start = (int)Math.ceil(Math.sqrt(start));
            int square_end = (int)Math.ceil(Math.sqrt(end));
            for(int i =square_start;i<=square_end;i++){
                if(i*i<=end){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}

Sherlock and Squares JavaScript Solution

function processData(input) {
    
    var data = input.split("\n");
    
    var T = data.shift();
    
    data.forEach(function(list){
        
        var range = list.split(" ");
        
        var min = Math.sqrt( parseInt(range[0], 10) );
        
        var max = Math.sqrt( parseInt(range[1], 10) );
        
        var diff = Math.floor(max) - Math.ceil(min) + 1;
        
        process.stdout.write(diff + "\n");
        
    });
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Sherlock and Squares Python Solution

import math
n = int(input())

for _ in range(n):
    temp = input().split()
    a = int(temp[0])
    b = int(temp[1])
    i = math.ceil(math.sqrt(a))
    num = 0
    while i * i <= b:
        num = num + 1
        i = i + 1
    print(num)
        

other solutions

  • HackerRank Library Fine Problem Solution
  • HackerRank Cut the sticks Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes