Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prime numbers with Java8 Stream API
import java.util.stream.IntStream;
class Main {
public static void main(String args[]) {
IntStream.rangeClosed(2, 100)
.filter(i -> IntStream.rangeClosed(2, (int)Math.sqrt(i))
.allMatch(j -> i%j != 0))
.forEach(n -> {
System.out.println(n);
});
}
}
@toderesa97

This comment has been minimized.

Copy link

toderesa97 commented Apr 10, 2018

Hi,

Quite inefficient, please refer to Miller-Rabin or Lehman test for checking the primality of a number.

@AhmedMYousseff

This comment has been minimized.

Copy link

AhmedMYousseff commented Nov 22, 2018

// check if number return true when it divided by it self and one only
IntPredicate isDivisible = index -> number % index == 0;
// test the number
isDivisible.test(number);
// check if numbers between 2 and the provided number is prime
return IntStream.range(2, number - 1).noneMatch(isDivisible);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.