C++ Solution: Sherlock and Squares Hackerrank

Sherlock and Squares


Code

#include <bits/stdc++.h>

using namespace std;


int main()

{

    int t,i;

    cin>>t;                                 // input no of testcases


    for(i=0;i<t;i++)

    {

        int a,b,y,total=0;

        float x;

        cin>>a>>b;                                 // input starting and ending point


        for(int j=a;j<=b;j++)                 // loop to find squares in the range

        {

            x=sqrt(j);                             // math function to calculate square root

            y=floor(x);                         // math function to get complete no

            if(x==y)                         // if both x and y are same then the number is a perfect square

            {

             total++;                     // increase the count

             j=(x+1)*(x+1)-1;     // since the current no is perfect square next perfect square will be (x+1)*(x+1) hence jump directly to that no this is done to reduce number of times the loop runs             

            }

        }

        cout<<total<<endl;

    }

    return 0;

}


Sherlock and Squares Hackerrank Solution in C++

You can post your own solutions in any language in comments section we will review and post with your credits.

Post a Comment

0 Comments