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):
s=0
for i in range(1, n 1,2):
s=s i
if s==n:
print(True)
else:
print(False)
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!
CodePudding user response:
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