VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-given-number-is-perfect-square-in-cpp/

⇱ Check if given number is perfect square - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if given number is perfect square

Last Updated : 17 Sep, 2024

Given a number n, check if it is a perfect square or not. 

Examples :

Input : n = 36
Output : Yes

Input : n = 2500
Output : Yes
Explanation: 2500 is a perfect square of 50

Input : n = 8
Output : No

Using sqrt()

  • Take the floor()ed square root of the number.
  • Multiply the square root twice.
  • Use boolean equal operator to verify if the product of square root is equal to the number given.

Code Implementation:


Output
Yes

Time Complexity: O(log(x))
Auxiliary Space: O(1)

Using ceil, floor and sqrt() functions

  • Use the floor and ceil and sqrt() function.
  • If they are equal that implies the number is a perfect square.

Code Implementation:


Output
Yes

Time Complexity : O(sqrt(n))
Auxiliary space: O(1)

Using Binary search:

Below is the implementation of the above approach:


Output
Yes

Time Complexity: O(log n)
Auxiliary Space: O(1)

Using Mathematical Properties:

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:


Output
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

Comment