Created
February 10, 2017 05:14
-
-
Save greymd/19ed7f18c0eba7e703ac2a6b69225ca8 to your computer and use it in GitHub Desktop.
Prime numbers with Java8 Stream API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} | |
} |
// 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
Hi,
Quite inefficient, please refer to Miller-Rabin or Lehman test for checking the primality of a number.