Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...