Your logic is incorrect. With sqnext = sq + 1
, you are calculating the next number and not the next square.
Try this:
import math
def find_next_square(sq):
# Return the next square if sq is a square, -1 otherwise
if math.sqrt(sq).is_integer:
sqnext = math.sqrt(sq) + 1
return sqnext * sqnext
else:
return -1
print(find_next_square(121))
EDIT
It looks like is_integer
method is flawed and gives incorrect values as pointed by Henry. The below code works for positive integers up to a certain limit.
import math
def find_next_square(sq):
# Return the next square if sq is a square, -1 otherwise
if int(math.sqrt(sq))**2 == sq:
sqnext = math.sqrt(sq)
return sqnext * sqnext
else:
return -1
print(find_next_square(5))
print(find_next_square(121))
Further since sqrt
doesn't work for negative numbers, that needs to be handled separately:
import math
def find_next_square(sq):
# Return the next square if sq is a square, -1 otherwise
sign = -1 if sq < 0 else 1
if int(math.sqrt(abs(sq)))**2 == abs(sq):
sqnext = math.sqrt(abs(sq)) + sign * 1
return sqnext * sqnext * sign
else:
return -1
print(find_next_square(5))
print(find_next_square(121))
print(find_next_square(-9))
Also, all the approaches above will not work for large numbers beyond a limit due to overflow issues.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…