A perfect square is a number that can be expressed as the square of an integer. For example, 4, 9, 16, and 25 are perfect squares because they are equal to 2^2, 3^2, 4^2, and 5^2, respectively.
In this article, we will create a Python program to check if a given number is a perfect square or not.
Understanding the Algorithm
To determine if a number is a perfect square, we need to find the square root of the given number and check if the square root is an integer. If the square root is an integer, then the number is a perfect square; otherwise, it is not.
Here is the step-by-step algorithm:
- Take the input number from the user.
- Calculate the square root of the input number using the math library.
- Check if the square root is an integer by comparing it with its integer value (rounded down).
- If the square root is equal to its integer value, then the number is a perfect square; otherwise, it is not.
Python Program to Check if a Number is a Perfect Square
import math
def is_perfect_square(num):
if num < 0:
return False
# Calculate the square root
square_root = math.isqrt(num)
# Check if the square root is equal to its integer value
return square_root * square_root == num
# Take input from the user
try:
number = int(input("Enter a number: "))
if is_perfect_square(number):
print(f"{number} is a perfect square.")
else:
print(f"{number} is not a perfect square.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
Explanation of the Code
We import the
math
module to use theisqrt()
function, which calculates the integer square root of a given number.The
is_perfect_square()
function takes an integernum
as input and returnsTrue
if it is a perfect square, otherwiseFalse
.In the
is_perfect_square()
function, we first check if the inputnum
is less than 0. If it is negative, we immediately returnFalse
because negative numbers cannot be perfect squares.Next, we calculate the square root of
num
using theisqrt()
function.Finally, we check if the square of the calculated
square_root
is equal tonum
. If the condition is true, thennum
is a perfect square, and the function returnsTrue
. Otherwise, it returnsFalse
.In the main program, we take user input for the number to be checked. We then call the
is_perfect_square()
function and print the result accordingly.
Testing the Program
Let's test the program with some sample inputs:
Input
Enter a number: 16
Output
16 is a perfect square.
That's all! The program works as expected and correctly identifies whether a number is a perfect square or not.