How to quickly check if the square root of an integer is an integer?
Hello everyone! I'm a beginner Java developer and I've encountered a problem: I need to determine whether the square root of an integer is an integer (i.e., the number is a perfect square). For example, 25 — yes (5), 26 — no.\n\nAt first I wrote this:\n\n```java\npublic static boolean isPerfectSquare(int n) {\n double sqrt = Math.sqrt(n);\n return sqrt == Math.floor(sqrt);\n}\n```\n\nBut then I thought: what if due to double precision errors this will work incorrectly for large numbers? For example, for n = 2147483647 (maximum int) or near the boundaries. Maybe it's better to use integer arithmetic? But how?\n\nI tried using a loop:\n\n```java\nfor (int i = 1; i * i <= n; i++) {\n if (i * i == n) return true;\n}\nreturn false;\n```\n\nBut this is terribly slow for large n. Is there a faster way?
No answers yet.
Log in to leave an answer
Blogs