Python Program to Check Perfect Square Number
import math and then verifying if math.isqrt(n) ** 2 == n where n is the number.Examples
How to Think About It
Algorithm
Code
import math def is_perfect_square(n): root = math.isqrt(n) return root * root == n 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.")
Dry Run
Let's trace the number 16 through the code
Input number
number = 16
Calculate integer square root
root = math.isqrt(16) = 4
Square the root
root * root = 4 * 4 = 16
Compare with original number
16 == 16 is True
Return result
Function returns True, so print '16 is a perfect square.'
| number | root | root*root | is_perfect_square |
|---|---|---|---|
| 16 | 4 | 16 | True |
Why This Works
Step 1: Calculate integer square root
Using math.isqrt(n) finds the largest integer less than or equal to the square root of n without decimals.
Step 2: Square the root
Squaring the integer root gives a number that is either equal to or less than n.
Step 3: Compare squared root with original
If the squared root equals n, then n is a perfect square; otherwise, it is not.
Alternative Approaches
import math def is_perfect_square(n): root = math.sqrt(n) return root.is_integer() 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.")
def is_perfect_square(n): if n < 0: return False i = 0 while i * i <= n: if i * i == n: return True i += 1 return False 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.")
Complexity: O(1) time, O(1) space
Time Complexity
Using math.isqrt() calculates the integer square root in constant time, so the check is O(1).
Space Complexity
The program uses a fixed amount of memory regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The math.isqrt() method is fastest and most reliable. The float method is fast but less precise. The loop method is slow and not recommended for large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| math.isqrt() | O(1) | O(1) | Fast and accurate for all integers |
| float sqrt and is_integer() | O(1) | O(1) | Simple but can fail on large numbers |
| Loop checking squares | O(√n) | O(1) | Educational or very small numbers only |
math.isqrt() for an accurate and fast perfect square check in Python 3.8+.