Finding if a number is a perfect square through sum of odd numbers


I’m stuck in this Python exercise:

A number n is a perfect square if, for some natural number k, it can be written as the sum of the first k odd numbers, that is, 1 + 3 +· · ·+k. The first five perfect squares are 1, 4, 9, 16 and 25. Write a function perfect_square(n) whose result is True, if n is a perfect square. Otherwise, the result must be False.

This is the solution I came up with:

def perfect_square(n):
    for i in range(1, n+1,2):
    if s==n:

When I tested the numbers of the question, 1 and 4 were correct, but from 9 the result is "False" when it should be True. Can someone please help me find what is wrong with my code? This is for an introductory class, so this is supposed to have a simple solution.
Thank you in advance!

Asked By: mari00



for some natural number k

You’re not given an exact k but we know the upper bound couldn’t be bigger than n so just check them all.

def perfect_square(n):
    summation = 0
    for value in range(1, n + 1, 2):
        summation += value
        if summation == n:
            return True
    return False
Answered By: Nathan McCoy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.