Генератор простых чисел
- import java.util.PrimitiveIterator;
- import java.util.Spliterator;
- import java.util.Spliterators;
- import java.util.function.LongPredicate;
- import java.util.stream.LongStream;
- import java.util.stream.StreamSupport;
- /**
- * Генерация простых чисел
- *
- * @author Kalter
- */
- public class PrimitiveNumberGenerator implements PrimitiveIterator.OfLong {
- public static LongStream finiteStream(LongPredicate predicate) {
- return stream(predicate, false);
- }
- public static LongStream finiteParallelStream(LongPredicate predicate) {
- return stream(predicate, true);
- }
- public static LongStream infiniteStream() {
- return stream(a -> true, false);
- }
- public static LongStream infiniteParallelStream() {
- return stream(a -> true, true);
- }
- private static LongStream stream(LongPredicate predicate, boolean parallel) {
- return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(
- new PrimitiveNumberGenerator(predicate), Spliterator.ORDERED), parallel);
- }
- private final LongPredicate predicate;
- private long primitiveNumber;
- protected PrimitiveNumberGenerator(LongPredicate predicate) {
- this.predicate = predicate;
- primitiveNumber = 1;
- }
- @Override
- public long nextLong() {
- primitiveNumber++;
- while (!isPrimitive(primitiveNumber)) {
- primitiveNumber++;
- }
- return primitiveNumber;
- }
- @Override
- public boolean hasNext() {
- return predicate.test(primitiveNumber);
- }
- private boolean isPrimitive(long number) {
- int r = 0;
- for (long i = 1; i <= number; i++) {
- if ((number % i) == 0) {
- r++;
- }
- }
- return r <= 2;
- }
- }
- //генерирует 10 простых чисел в пределах от 10 до 100
- PrimitiveNumberGenerator
- .infiniteStream()
- .filter(p -> p > 10 && p < 100)
- .limit(10)
- .forEach(System.out::println);
- //генерирует первые 666 простых чисел
- PrimitiveNumberGenerator
- .infiniteStream()
- .limit(666)
- .forEach(System.out::println);