Check if given number is perfect square in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether the number n is perfect square or not. A number is said to be a perfect square number when its square root is an integer.

So, if the input is like n = 36, then the output will be True as 36 = 6*6.

To solve this, we will follow these steps −

• sq_root := integer part of (square root of n)
• return true when sq_root^2 is same as n otherwise false

Example

Let us see the following implementation to get better understanding −

Live Demo

from math import sqrt
def solve(n):
sq_root = int(sqrt(n))
return (sq_root*sq_root) == n
n = 36
print (solve(n))

Input

36

Output

True
Published on 18-Jan-2021 12:51:46