![]() |
VOOZH | about |
Given a positive integer n, check if it is perfect square or not using only addition/subtraction operations and in minimum time complexity.
Examples :
Input : n = 36
Output : YesInput : n = 2500
Output : Yes
Explanation: 2500 is a perfect square of 50Input : n = 8
Output : No
We can use the property of odd number for this purpose:
Addition of first n odd numbers is always perfect square
1 + 3 = 4,
1 + 3 + 5 = 9,
1 + 3 + 5 + 7 + 9 + 11 = 36 ...Below is the implementation of above idea :
Output :
No
Yes
How does this work?
Below is explanation of above approach.
1 + 3 + 5 + ... (2n-1) = ∑(2*i - 1) where 1<=i<=n = 2*(∑(i) - ∑(1)) where 1<=i<=n = 2n(n+1)/2 - n = n(n+1) - n = n2
Please refer the above article for all approaches and detailed explanation.