15,792,397 members
See more:
I have used:

int(math.sqrt(last) - math.sqrt(first))

for getting the answer, whereas it is not working for some test-cases. So, can anyone suggest me a fast algorithm for the above question.
Posted
Updated 17-Nov-22 14:19pm
v2
joshrduncan2012 20-Mar-14 11:34am
Why isn't this working for some test cases?

Have you tried searching on google for something related to this?
YvesDaoust 31-Mar-14 5:31am
You do not specify if the first and last bounds are considered to be "between" as well.

## Solution 1

I think you need the number of integer between the first integer after sqrt(first) and before sqrt(last).

To get the first integer after, you can use `Math.Ceiling`.

To get the first integer before, you can use `Math.Floor`.

Then the complete formula should be :
C#
`Math.Floor(Math.Sqrt(last)) - Math.Ceiling(Math.Sqrt(first)) + 1`

+1 because if the first integer before last is the first integer after first, the difference will be 0 but you have 1 integer.

For example : with sqrt(first) = 2.3 and sqrt(last) = 3.2
you have 1 integer between the two numbers = 3 but Floor(3.2)=3 and Ceiling(2.3)=3
and Floor(3.2)-Ceiling(2.3) = 0.

This code is written using C#, but I'm sure you can found the `floor` and `ceiling` functions in other language.

Jalem Raj Rohit 20-Mar-14 12:57pm
Thank you buddy.
This has helped me very much.

## Solution 2

Python
```import math
N = int(input())

for i in range(0,N):
first,last = map(int,input().split(" "))
print(math.floor(math.sqrt(last)) - math.ceil(math.sqrt(first)) + 1)```

## Solution 3

The number of perfect squares between 0 and N (both inclusive), is the integer square root of N, let `isqrt(N)`.

So the number of perfect squares between first and last (bounds inclusive), is the difference `isqrt(last) - isqrt(first - 1)`.

The integer square root can be computed as the square root cast to int,
Python
`int(math.sqrt(last)) - int(math.sqrt(first - 1))`

v5