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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With