How to quickly determine if the square root of an integer is an integer in Java?
Hello everyone! I'm a beginner Java developer and I've encountered a problem: I need to check if the square root of an integer is an integer (i.e., a perfect square). For example, for 16 the answer is true (4), for 20 — false.
I wrote a simple method with a loop, but it works slowly for large numbers (e.g., 10^12). I tried Math.sqrt(), but I'm afraid of double rounding errors. Here's my current code:
```java
public static boolean isPerfectSquare(int n) {
if (n < 0) return false;
for (int i = 0; i * i <= n; i++) {
if (i * i == n) return true;
}
return false;
}
```
It works, but for n = 2_147_483_647 (maximum int) the loop executes ~46340 iterations, which is slow. I've heard that you can use binary search or tricks with floating point numbers. But how to do it correctly?
No answers yet.
Log in to leave an answer
Blogs
Java for Machine Learning: Capabilities and Limitations
Generics in C#: Why They Are Needed and How to Use Them