~2 min read • Updated Oct 7, 2025
Program Overview
This Python program checks whether a given number is a perfect square.
Instead of using square roots, it uses a mathematical property:
A number is a perfect square if it equals the sum of consecutive odd numbers starting from 1.
Examples:
- √9 = 1 + 3 + 5
- √16 = 1 + 3 + 5 + 7
- √4 = 1 + 3
Python Code:
def is_perfect_square_by_odd_sum(n):
total = 0
odd = 1
while total < n:
total += odd
odd += 2
return total == n
# Run the program
num = int(input("Enter a number: "))
if is_perfect_square_by_odd_sum(num):
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")
Sample Output:
Enter a number: 16
16 is a perfect square.
Enter a number: 20
20 is not a perfect square.
Step-by-Step Explanation:
- Start with the first odd number: 1
- Keep adding consecutive odd numbers: 1, 3, 5, 7, ...
- Stop when the total reaches or exceeds the input number
- If the total equals the input, it's a perfect square
Written & researched by Dr. Shahin Siami