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
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",&t);
while(t--)
{
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)
squares++;
}
Console.WriteLine(squares);
}
}
}
Attempt Sherlock and Squares HackerRank Challenge
Link – https://www.hackerrank.com/challenges/sherlock-and-squares/
Next HackerRank Challenge Solution
Link – https://exploringbits.com/library-fine-hackerrank-solution/
Aayush Kumar Gupta is the founder and creator of ExploringBits, a website dedicated to providing useful content for people passionate about Engineering and Technology. Aayush has completed his Bachelor of Technology (Computer Science & Engineering) from 2018-2022. From July 2022, Aayush has been working as a full-time Devops Engineer.