Any number which can be expressed as the product of two whole equal numbers is classified as a perfect square. For example, 64 can be written as 8*8 hence 64 is a perfect square. In this article, we will create a Python program to check whether the number is a perfect square or not.
Algorithm To Check If A Number Is A Perfect Square Or Not
Step 1: Take the input from the user
Step 2: Compute the square root of the given number using the math library
Step 3: Checking whether the int(root + 0.5) ** 2 == number, if this evaluates to True then the number is a perfect square
Python Program To Check If A Number Is A Perfect Square
# Taking the input from user
number = int(input("Enter the Number"))
root = math.sqrt(number)
if int(root + 0.5) ** 2 == number:
print(number, "is a perfect square")
print(number, "is not a perfect square")
First, we are importing the math library in our program then we are taking the input from the user and converting it to integer just in case the user inputs a float number.
The square root of the number is calculated with
math.sqrt the method and the result is stored in
root a variable. Next, we are checking whether the integer value of the square of
root+0.5 is equal to the number itself if this evaluates to True, then the number is a perfect square else it is not.
Notice we are adding 0.5 to the root because in the case of a large number the root may not be a perfect whole number it might be some decimal less. However, as it is known the
int() method takes the floor value adding 0.5 to the float number is a reliable solution to get the desired outputs even if the input is large.
Running the program for some test cases gave the following output,
Enter the Number 444
444 is not a perfect square
Enter the Number 64
64 is a perfect square
Enter the Number 81
81 is a perfect square
Enter the Number 998001
998001 is a perfect square