Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - Is there a way to find the next perfect square?

This is my code, however it only returns the next number (eg taking 121 it returns 122 instead of 144), but I dont understand why.

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 = sq + 1
        if math.sqrt(sqnext).is_integer:
            return sqnext
    else:
        return -1
question from:https://stackoverflow.com/questions/65902051/is-there-a-way-to-find-the-next-perfect-square

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...