2
public static boolean checkSquare(int i){
    return IntStream
            .rangeClosed(1, i/2)
            .anyMatch(x -> Math.sqrt(x) == i);
}

When I enter 1 as an user input, it return false. I don't understand why square root of 1 is not equals to 1. Can anyone tell me is my code correct?

Jongware
  • 21,058
  • 8
  • 43
  • 86
  • 1
    Further reading: [Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0) – LuCio Oct 10 '18 at 06:34
  • Do *not* change an existing question to something entirely else, please. – Jongware Oct 10 '18 at 20:56

1 Answers1

4

If your user input is assigned your i variable, it's clear why

IntStream.rangeClosed(1, i/2).anyMatch(x -> Math.sqrt(x) == i);

returns false when i==1, since 1/2 == 0, so IntStream.rangeClosed(1, 0) is an empty stream.

Change your method to:

public static boolean checkSquare(int i){
    return IntStream
            .rangeClosed(1, i)
            .anyMatch(x -> Math.sqrt(x) == i);
}

or, if you really want to keep the optimization of halving the size of the IntStream:

public static boolean checkSquare(int i) {
    return IntStream
            .rangeClosed(1, Math.max(1,i/2))
            .anyMatch(x -> Math.sqrt(x) == i);
}
Eran
  • 359,724
  • 45
  • 626
  • 694