![]() |
VOOZH | about |
Given a number n, check if it is a perfect square or not.
Examples :
Input : n = 36
Output : YesInput : n = 2500
Output : Yes
Explanation: 2500 is a perfect square of 50Input : n = 8
Output : No
Table of Content
Code Implementation:
Yes
Time Complexity: O(log(x))
Auxiliary Space: O(1)
Code Implementation:
Yes
Time Complexity : O(sqrt(n))
Auxiliary space: O(1)
Below is the implementation of the above approach:
Yes
Time Complexity: O(log n)
Auxiliary Space: O(1)
The idea is based on the fact that perfect squares are always some of first few odd numbers.
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
1 + 3 + 5 + 7 + 9 = 25
1 + 3 + 5 + 7 + 9 + 11 = 36
......................................................
Code Implementation:
Yes
How does this work?
1 + 3 + 5 + ... (2n-1) = Sum(2*i - 1) where 1<=i<=n
= 2*Sum(i) - Sum(1) where 1<=i<=n
= 2n(n+1)/2 - n
= n(n+1) - n
= n2'
Time ComplexityAnalysis
Let us assume that the above loop runs i times. The following series would have i terms.
1 + 3 + 5 ........ = n [Let there be i terms]
1 + (1 + 2) + (1 + 2 + 2) + ........ = n [Let there be i terms]
(1 + 1 + ..... i-times) + (2 + 4 + 6 .... (i-1)-times) = n
i + (2^(i-1) - 1) = n
2^(i-1) = n + 1 - i
Using this expression, we can say that i is upper bounded by Log n