patterncMinor
Efficient way of finding perfect squares
Viewed 0 times
perfectefficientwaysquaresfinding
Problem
I was trying to solve a problem which needed you to count the number of perfect squares in the given range:
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?
#include
#include
#include
#include
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",&testcases);
while(testcases--)
{
int counter =0;
scanf("%d %d",&a,&b);
unsigned int i;
for(i=a;i<=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?
Solution
You could easily find the number of perfect squares up to (and including) a number by simply using
If you want the number of squares between two numbers, you should simply need to do this:
Though note if
(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.Code Snippets
(int)sqrt(max) - (int)sqrt(min)Context
StackExchange Code Review Q#78525, answer score: 6
Revisions (0)
No revisions yet.