Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Prime numbers with Java8 Stream API
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 -> {

This comment has been minimized.

Copy link

@toderesa97 toderesa97 commented Apr 10, 2018


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


This comment has been minimized.

Copy link

@AhmedMYousseff 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
// 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.