Skip to content

Commit

Permalink
Attempt p7 in Java (4)
Browse files Browse the repository at this point in the history
  • Loading branch information
LivInTheLookingGlass committed Sep 16, 2024
1 parent c190368 commit cb148ba
Showing 1 changed file with 38 additions and 9 deletions.
47 changes: 38 additions & 9 deletions java/src/main/java/euler/lib/Primes.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
Expand All @@ -24,15 +26,47 @@ private static class Cache {

// Generate an infinite stream of primes
public static Stream<Long> primes() {
return StreamSupport.stream(new PrimeIterator(null), false);
return StreamSupport.stream(new PrimeSpliterator(null), false);
}

// Generate a stream of primes up to a given limit
public static Stream<Long> primesUntil(Long limit) {
return StreamSupport.stream(new PrimeIterator(limit), false);
return StreamSupport.stream(new PrimeSpliterator(limit), false);
}

private static class PrimeIterator implements Iterator<Long>, Iterable<Long> {
private static class PrimeSpliterator implements Spliterator<Long> {
private final PrimeIterator primeIterator;

PrimeSpliterator(Long limit) {
primeIterator = new PrimeIterator(limit);
}

@Override
public boolean tryAdvance(Consumer<? super Long> action) {
if (primeIterator.hasNext()) {
action.accept(primeIterator.next());
return true;
}
return false;
}

@Override
public Spliterator<Long> trySplit() {
return null; // Sequential iteration only
}

@Override
public long estimateSize() {
return Long.MAX_VALUE; // Unknown size
}

@Override
public int characteristics() {
return ORDERED | SIZED | IMMUTABLE | NONNULL;
}
}

private static class PrimeIterator implements Iterator<Long> {
private final Long limit;
private Iterator<Long> primeGenerator;
private boolean exhausted = false; // Flag to indicate if we have exhausted all primes
Expand Down Expand Up @@ -81,11 +115,6 @@ public Long next() {
primeGenerator = new PrimeGeneratorIterator();
}
}

@Override
public Iterator<Long> iterator() {
return this;
}
}

private static class PrimeGeneratorIterator implements Iterator<Long> {
Expand All @@ -102,7 +131,7 @@ private static class PrimeGeneratorIterator implements Iterator<Long> {
sieve.put(prime, step);
step = prime * 2;
});
recursivePrimes = new PrimeIterator();
recursivePrimes = new PrimeIterator(null);
if (recursivePrimes.hasNext()) {
currentPrime = recursivePrimes.next();
}
Expand Down

0 comments on commit cb148ba

Please sign in to comment.