0
public static boolean isSquare(int n) {
if (n < 0) {     
  return false;
}
if (n == 0) {
  return true;
}
for (int i = 0; i <= n; i++) {
  if (i * i == n) {     //checks if no. is perfect square//     
    return true;
  }
}
return false;
}

why isn't this code working for some numbers such as 219433929?

Elachi
  • 3
  • 1
  • 3
  • 1
    there is a maximal number that can be represented by `int` (`Integer.MAX_VALUE`) - see Java Language Specification [4.2.1. Integral Types and Values](https://docs.oracle.com/javase/specs/jls/se18/html/jls-4.html#jls-4.2.1-100-C): "*ranges: ... For int, from -2147483648 to 2147483647, inclusive*" - maybe do the calculation/comparison with `long` – user16320675 Jun 04 '22 at 11:15
  • 1
    You're experiencing [integer overflow](https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.17.1) during calculation of `i*i`, and only the low order 32 bits of the product are retained. At i=10315427, the low-order 32-bits of `i*i` equals 219433929. Java does not throw an exception when integer overflow occurs as a result of an arithmetic operation. As others have noted, you can make `i` a `long`, but you should also consider a better sqrt algorithm. Look at the "Related" links for better algorithms. – President James K. Polk Jun 04 '22 at 13:44

0 Answers0