0

I am trying to write an if statement to check to see if the amount of numbers a user enters into the array is a perfect square (4, 9, 25, 36...).

if(array.length != Math.sqrt(array))

I know this isn't correct and I know it is probably something easy, but I can't seem to get how to think of an if statement to see if my array is a number that is a perfect square.

Any help is appreciated, thank you.

Pang
  • 9,564
  • 146
  • 81
  • 122
TyngeOfTheGinge
  • 524
  • 1
  • 4
  • 14
  • http://stackoverflow.com/questions/30919111/whats-the-best-way-in-javascript-to-test-if-a-given-parameter-is-a-square-numbe – Pang Mar 17 '16 at 00:56
  • if(issquare(array.length)) will evaluate true of the length of the array is a square. – DisplayName Mar 17 '16 at 00:59

2 Answers2

2

Try this:

int root = (int)Math.sqrt(array.length);
boolean isSquare = root * root == array.length;

Or

if ((int)Math.sqrt(array.length) == Math.sqrt(array.length))

There are other ways too, but they all would employ the fact that the square root should be a whole number.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

There are similar answers for other languages, but this algorithm should work with what you're doing:

bool IsPerfectSquare(long input)
{
    long SquareRoot = (long) Math.Sqrt(input);
    return ((SquareRoot * SquareRoot) == input);
}

see this link for more info:

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

Community
  • 1
  • 1
brw59
  • 502
  • 4
  • 19
  • This is another great way to do it: http://stackoverflow.com/questions/12862637/perfect-square-or-not – brw59 Mar 17 '16 at 01:09