Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding perfect square

Tags:

python

I have this python code:

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)

the output is:

16 is not a perfect square.

Whereas this works perfectly:

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'

What am I doing wrong?

like image 351
eozzy Avatar asked Nov 25 '25 22:11

eozzy


1 Answers

Just thought I'd contribute a simpler solution:

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

This is valid for n < 2**52 + 2**27 = 4503599761588224.

Examples:

>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True
like image 173
Sunjay Varma Avatar answered Nov 28 '25 13:11

Sunjay Varma