Skip to main content
 首页 » 编程设计

python之寻找完美的正方形

2025年05月04日10del

我有这个 python 代码:

def sqrt(x): 
    ans = 0 
    if x >= 0: 
        while ans*ans < x: 
            ans = ans + 1 
            if ans*ans != x: 
                print x, 'is not a perfect square.' 
                return None 
            else: 
                print x, ' is a perfect square.' 
                return ans 
    else: 
        print x, ' is not a positive number.' 
        return None 
 
y = 16       
sqrt(y) 

输出是:

16 is not a perfect square. 

虽然这很完美:

x = 16 
ans = 0 
if x >= 0: 
    while ans*ans < x: 
        ans = ans + 1 
        #print 'ans =', ans 
    if ans*ans != x: 
        print x, 'is not a perfect square'   
    else: print ans, 'is a perfect square' 
else: print x, 'is not a positive number' 

我做错了什么?

请您参考如下方法:

只是想我会提供一个更简单的解决方案:

def is_square(n): 
    return sqrt(n).is_integer() 

这对 n < 2**52 + 2**27 = 4503599761588224 有效.

例子:

>>> is_square(4) 
True 
>>> is_square(123) 
False 
>>> is_square(123123123432**2) 
True