How to check if a number is a perfect square in Python
Let’s learn how to check if a number is a perfect square number in Python. Here we need to use Math module of python to check the number.
Check if a number is a perfect square or not in Python
Perfect Square Number: When a number is expressed as the product of two equal numbers, then that number is said to be a perfect square number. For example:- 25 is a perfect square as it can be expressed as a product of 5*5, 81 is also a perfect square as it can be expressed as a product of 9*9.
List of perfect square numbers between 1 to 100 are :-
- 1 = 1*1
- 4 = 2*2
- 9 = 3*3
- 16 = 4*4
- 25 = 5*5
- 36 = 6*6
- 49 = 7*7
- 64 = 8*8
- 91 = 9*9
- 100 = 10*10
Steps to check perfect square number in Python:
- Step 1:- Import the math module.
- Step 2:- Find the square root of the given number using the math.sqrt(), and store that value in a variable. ( You can learn: Mathematical Functions in Python )
- Step 3:- Subtract the value obtained after taking the floor/round of the value stored in the variable from the given original number.
- Step 4:- If the final result is equal to ZERO, then the given number is a perfect square number.
Python program to check if a number is perfect square or not
import math n=121 x=math.sqrt(n) y=(x-math.floor(x)) print("Difference between the square root of a number and the given number is",y) if(y==0): print("Perfect Square Number") else: print("Not Perfect Square Number")
Output:
Difference between the square root of a number and the given number is 0.0 Perfect Square Number
Another example where n = 127
import math n=127 x=math.sqrt(n) y=(x-math.floor(x)) print("Difference between the square root of a number and the given number is",y) if(y==0): print("Perfect Square Number") else: print("Not Perfect Square Number")
Output:
Difference between the square root of a number and the given number is 0.26942766958464404 Not Perfect Square Number
Leave a Reply