Efficient way of finding perfect squares I was trying to solve a problem which needed you to count the number of perfect squares in the given range:

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;math.h&gt;
#include &lt;stdlib.h&gt;
int isPerfectSquare(int x)
{
    float s = sqrt(x);
    if (fmod(s,1) ==0)
        return 1;
    else
        return 0;
}
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int testcases;
    unsigned int a,b;
    scanf("%d",&amp;testcases);
    while(testcases--)
        {
        int counter =0;
        scanf("%d %d",&amp;a,&amp;b);
        unsigned int i;
        for(i=a;i&lt;=b;i++)
            {
                int last_digit = i%10;
            if( (last_digit == 2) || (last_digit == 3) || (last_digit == 7) || (last_digit == 8) )
                continue;
            else
            {
                if (isPerfectSquare(i))
                    counter++;
            }
        }
        printf("%d\n",counter);
    }
    return 0;
}


However, this code fails for certain test cases due to a timeout. I found that perfect squares do not end with a 2 or 3 or 7 or 8 so I ignored such values. Yet, I'm unable to solve this problem within the required run time.

I have found similar questions here, but either they were not in C or they didn't have answers that were quite relevant to C.

Could you suggest a way that I can optimize this code so that it could run faster?
You could easily find the number of perfect squares up to (and including) a number by simply using (int)sqrt(x)

If you want the number of squares between two numbers, you should simply need to do this:

(int)sqrt(max) - (int)sqrt(min)


Though note if min is a perfect square, it is excluded/subtracted from the range. You can use a +/- 1 if you want to exclude the max number (if it's a perfect square), or include the min number (if it's a perfect square), from the range.