2

I am trying to check if a large number is a perfect square. Here is the corresponding part of my code:

x = long(raw_input())
a = sqrt(5 * x ** 2 + 4)
b = sqrt(5 * x **2 - 4)
if long(a) == a or long(b) == b:
    print "YES"
else:
    print "NO" 

However, when x becomes too large, I get this error:

    a = sqrt(5 * x ** 2 + 4)
OverflowError: long int too large to convert to float

Can anybody tell me a workaround for this?

xrisk
  • 3,790
  • 22
  • 45
  • You could try [Newton's method](http://stackoverflow.com/questions/12850100/finding-the-square-root-using-newtons-method-errors). – erip May 27 '15 at 18:37
  • There are better ways for determining if a number is a perfect square (see [this](http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer), for example). – arshajii May 27 '15 at 18:38
  • @erip you mean python can’t do this ? – xrisk May 27 '15 at 18:39
  • You're using the wrong algorithm. Try to find something that doesn't rely on big numbers. – Mark Ransom May 27 '15 at 18:40
  • @xrisk if you looked at the link, it was implemented in Python. In any case, I think arshajii's solution is smarter. – erip May 27 '15 at 18:40
  • You could use higher precision numbers. http://stackoverflow.com/questions/6663272/double-precision-floating-values-in-python – Christian Sarofeen May 27 '15 at 18:41

1 Answers1

2

Use the decimal module to take the square root of large numbers.

hazydev
  • 344
  • 1
  • 9