Below is the code I have written for counting perfect squares between a given lower and upper bound.
I am using the following concept to solve this:
Starting with 1, there are \$\sqrt{m}\$ square numbers up to and including \$m\$.
public static int CountPerfectSquares(long A, long B)
{
int count = 0;
//Proceed if lowerbound is less than upperbound
if (A < B)
{
//negative numbers are not perfect squares
if (A < 0 && B < 0) return count;
//Reset lowerbound if required
if (A <= 0) A = 1;
//Find number of squares between A & B (INCLUSIVE lower and upperbound)
//count = (int)Math.Sqrt(B) - (int)Math.Sqrt(A); //Giving wrong count when LowerBound value is a whole square (For exp. CountPerfectSquares(1, 25))
int sqrtA = (int)Math.Sqrt(A);
int sqrtB = (int)Math.Sqrt(B);
count = sqrtB - sqrtA;
//To handle the case when lowerbound value is a perfect square number
if (A == sqrtA * sqrtA)
{
count++;
}
}
return count;
}
Can you please help me make this more efficient, if possible?
Is there any other way of handling the case when the lower bound value is a perfect square number, so that I don't have to do an extra count++
?