![]() |
VOOZH | about |
Given two numbers a and b where 1<=a<=b, find the number of perfect squares between a and b (a and b inclusive).
Example
Input: a = 3, b = 8
Output: 1
Explanation: The only perfect square in given range is 4.
Input: a = 9, b = 25
Output: 3
Explanation: The three perfect squares in given range are 9, 16 and 25
Table of Content
The idea for this approach is to use a loop to iterate from a to b and count the numbers that are perfect squares.
Count of squares is 3
Time Complexity: O((b-a) * sqrt(b)).
Auxiliary Space: O(1)
The idea for this approach is to simply take square root of ‘a’ and ‘b’ and count the numbers between them by using this formula floor(sqrt(b)) - ceil(sqrt(a)) + 1
We take floor of sqrt(b) because we need to consider numbers before b.
We take ceil of sqrt(a) because we need to consider numbers after a.
Example: b = 24, a = 8.
floor(sqrt(b)) = 4, ceil(sqrt(a)) = 3.
And number of squares is 4 - 3 + 1 = 2.(9 and 16) .
Count of squares is 3
Time Complexity: O(log b) as any typical implementation of square root for a number n takes time equal to O(Log n)
Auxiliary Space: O(1)