isPerfectSquare function

bool isPerfectSquare (int number)

Find out whether the provided integer is a perfect square, i.e. a square of an integer.

True if and only if it is a perfect square.

Implementation

bool isPerfectSquare(int number) {
  if (number < 0) {
    return false;
  }

  int lastHexDigit = number & 0xF;
  if (lastHexDigit > 9) {
    return false; // return immediately in 6 cases out of 16.
  }

  if (lastHexDigit == 0 ||
      lastHexDigit == 1 ||
      lastHexDigit == 4 ||
      lastHexDigit == 9) {
    int t = (sqrt(number) + 0.5).floor();
    return (t * t) == number;
  }

  return false;
}