How could I check if a number is a perfect square?
Speed is of no concern, for now, just working.
See also: Integer square root in python.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem with relying on any floating point computation (
math.sqrt(x), orx**0.5) is that you can’t really be sure it’s exact (for sufficiently large integersx, it won’t be, and might even overflow). Fortunately (if one’s in no hurry;-) there are many pure integer approaches, such as the following…:Hint: it’s based on the “Babylonian algorithm” for square root, see wikipedia. It does work for any positive number for which you have enough memory for the computation to proceed to completion;-).
Edit: let’s see an example…
this prints, as desired (and in a reasonable amount of time, too;-):
Please, before you propose solutions based on floating point intermediate results, make sure they work correctly on this simple example — it’s not that hard (you just need a few extra checks in case the sqrt computed is a little off), just takes a bit of care.
And then try with
x**7and find clever way to work around the problem you’ll get,you’ll have to get more and more clever as the numbers keep growing, of course.
If I was in a hurry, of course, I’d use gmpy — but then, I’m clearly biased;-).
Yeah, I know, that’s just so easy it feels like cheating (a bit the way I feel towards Python in general;-) — no cleverness at all, just perfect directness and simplicity (and, in the case of gmpy, sheer speed;-)…