Check for Perfect Square in Python
Check for Perfect Square in Python
Here on this page, we will learn how to Check for Perfect Square in Python programming language. We are given an integer number and need to print “True” if it is, otherwise “False”.
Algorithm ( Method 1 )
- Take the floor() value square root of the number.
- Multiply the square root twice.
- We use the Boolean equal operator to verify if the product of the square root is equal to the number given.
Python Code
Run
from math import sqrt def isPerfectSquare(x): if x >= 0: sr = int(sqrt(x)) return (sr * sr) == x return False n = 84 if isPerfectSquare(n): print("True") else: print("False")
Output
False
Algorithm ( Method 2 )
- In this method we use the floor and ceil function.
- If they are equal that implies the number is a perfect square.
Run
import math def checkperfectsquare(x): if (math.ceil(math.sqrt(n)) == math.floor(math.sqrt(n))): print("True") else: print("False") n = 49 checkperfectsquare(n)
Output
True
For similar Questions click on the given button
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
num=int(input())
if num<0:
print('negative')
else:
for i in range(1,n):
if i*i==num:
print(i)
Kindly refer to our discord community for all your technical doubts.
import math
num=int(input())
x=math.sqrt(num)
y=int(x)
a=y*y
if num==a:
print(“perfect square”)
else:
print(“not a perfect square”)