I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell
boolean isPrime(int n) {
for (int i
You should use IntStream.noneMatch there as:
boolean isPrimeStream(int n) {
return IntStream.range(2, n) // note division by zero possible in your attempt
.noneMatch(i -> n % i == 0);
}
Edit: As pointed in comments by Andreas, using range(2, n) to avoid division by zero and since division by 1 would always lead to the condition being true and returning the result as false otherwise.
Returns whether no elements of this stream match the provided predicate
Your current code is using IntStream.anyMatch
Returns whether any elements of this stream match the provided predicate
which is why it would return true if the condition specified is satisfied for any input instead of when the method is supposed to return false.
how to do similar to for loop above
With java-9 or above you could use IntStrem.iterate as
private boolean isPrimeStream(int n) {
return IntStream.iterate(2, i -> i * i <= n, i -> i + 1) // similar to the loop
.noneMatch(i -> n % i == 0);
}