Skip to content

Instantly share code, notes, and snippets.

@greymd
Created February 10, 2017 05:14
Show Gist options
  • Save greymd/19ed7f18c0eba7e703ac2a6b69225ca8 to your computer and use it in GitHub Desktop.
Save greymd/19ed7f18c0eba7e703ac2a6b69225ca8 to your computer and use it in GitHub Desktop.
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
Copy link

Hi,

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

@AhmedMYousseff
Copy link

// 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