Senior
public static boolean isPerfectSquare(int n){ if (n < 0) return false; int sqrt = (int) Math.sqrt(n); return sqrt * sqrt == n; }
sobes.tech AI
Answer from AI
This method checks whether the number n is a perfect square of an integer.
Algorithm:
- If
nis negative, immediately returnfalse, as negative numbers cannot be perfect squares. - Calculate the integer square root
sqrtusingMath.sqrt(n)and casting toint. - Check if the square of
sqrt(sqrt * sqrt) equals the original numbern. If yes — the number is a perfect square.
Example usage:
System.out.println(isPerfectSquare(16)); // true
System.out.println(isPerfectSquare(20)); // false