31

Possible Duplicate:
What's a good algorithm to determine if an input is a perfect square?

I want Shortest and Simplest way to Check a number is perfect square in C#

Some of Perfect Squares:

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
Community
  • 1
  • 1
Javed Akram
  • 15,024
  • 26
  • 81
  • 118

4 Answers4

53

Probably checking if the square root of the number has any decimal part, or if it is a whole number.

Implementationwise, I would consider something like this:

double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;

isSquare should now be true for all squares, and false for all others.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • 10
    +1: I was surprised that the % operator works on doubles – Binary Worrier Feb 03 '11 at 12:17
  • 14
    The above answer is not always correct with large number. Try with this: double result = Math.Sqrt ( 3999680306388005621 ); bool isSquare = result % 1 == 0; long x = ( long ) result; long y = x * x; // y is not 3999680306388005621 – Setyo N Oct 26 '12 at 07:56
  • I'm not sure but that might be when the number starts to lose precision / floating point? – Luke Aug 02 '17 at 12:16
7

This is a variant on checking if the square root is integral:

bool IsPerfectSquare(double input)
{
    var sqrt = Math.Sqrt(input);
    return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}

Math.Ceiling will round up to the next integer, whereas Math.Floor will round down. If they are the same, well, then you have an integer!

This can also be written as a oneliner:

if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • 2
    `Math.Ceiling()` and `Math.Floor()` return a double value, so you'll run into possible issues here. Instead, do a floating point comparison: `if (Math.Abs(val1 - valu2) < Double.Epsilon) { ... }` – michael Mar 09 '14 at 19:53
  • @michael, thank you, that is a very good point! I have updated my answer to reflect this! – Daren Thomas Mar 10 '14 at 10:32
  • Any reason to do `< Double.Epsilon` instead of `> 0`? – j.i.h. Sep 17 '14 at 13:17
5
    public bool IsPerferctSquare(uint number)
    {
        return (Math.Sqrt(number) % 1 == 0);
    }
rajesh
  • 285
  • 4
  • 16
2
public bool IsPerfectSquare(int num)
{
   int root = (int)Math.Sqrt(num);
   return (int) Math.Pow(root,2) == num;
}
Sebazzz
  • 1,205
  • 2
  • 15
  • 33
Itay Karo
  • 17,924
  • 4
  • 40
  • 58