What’s a good algorithm to determine if an input is a perfect square? [duplicate]

bool IsPerfectSquare(long input) { long closestRoot = (long) Math.Sqrt(input); return input == closestRoot * closestRoot; } This may get away from some of the problems of just checking “is the square root an integer” but possibly not all. You potentially need to get a little bit funkier: bool IsPerfectSquare(long input) { double root = Math.Sqrt(input); … Read more

Check if a number is a perfect square

The problem with relying on any floating point computation (math.sqrt(x), or x**0.5) is that you can’t really be sure it’s exact (for sufficiently large integers x, 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…: def is_square(apositiveint): x = apositiveint // … Read more

Fastest way to determine if an integer’s square root is an integer

I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don’t know how the Java factor will play out. My approach is threefold: First, filter out obvious answers. This includes negative numbers and looking at … Read more

tech