Skip to content

Commit

Permalink
Attempt p7 in Java (3)
Browse files Browse the repository at this point in the history
  • Loading branch information
LivInTheLookingGlass committed Sep 16, 2024
1 parent 6256208 commit c190368
Showing 1 changed file with 9 additions and 16 deletions.
25 changes: 9 additions & 16 deletions java/src/main/java/euler/lib/Primes.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
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,12 +22,14 @@ private static class Cache {

private static final Cache CACHE = new Cache(0, new ArrayList<>());

// Generate an infinite stream of primes
public static Stream<Long> primes() {
return StreamSupport.stream(new PrimeIterator(null).spliterator(), false);
return StreamSupport.stream(new PrimeIterator(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).spliterator(), false);
return StreamSupport.stream(new PrimeIterator(limit), false);
}

private static class PrimeIterator implements Iterator<Long>, Iterable<Long> {
Expand All @@ -39,8 +39,7 @@ private static class PrimeIterator implements Iterator<Long>, Iterable<Long> {

PrimeIterator(Long limit) {
this.limit = limit;
// Initialize primeGenerator with a recursive prime generator
primeGenerator = new PrimeGeneratorIterator(null);
primeGenerator = new PrimeGeneratorIterator();
}

@Override
Expand Down Expand Up @@ -79,15 +78,10 @@ public Long next() {
}

// Reinitialize primeGenerator if needed
primeGenerator = new PrimeGeneratorIterator(null);
primeGenerator = new PrimeGeneratorIterator();
}
}

@Override
public Spliterator<Long> spliterator() {
return Spliterators.spliteratorUnknownSize(this, Spliterator.ORDERED);
}

@Override
public Iterator<Long> iterator() {
return this;
Expand All @@ -103,13 +97,12 @@ private static class PrimeGeneratorIterator implements Iterator<Long> {
private long step = 2;
private long candidate = 9;

PrimeGeneratorIterator(Long stop) {
// Initialize with initial primes and state
PrimeGeneratorIterator() {
initialPrimes.forEach(prime -> {
sieve.put(prime, step);
step = prime * 2;
});
recursivePrimes = new PrimeGeneratorIterator(null);
recursivePrimes = new PrimeIterator();
if (recursivePrimes.hasNext()) {
currentPrime = recursivePrimes.next();
}
Expand All @@ -121,7 +114,7 @@ private static class PrimeGeneratorIterator implements Iterator<Long> {

@Override
public boolean hasNext() {
return true; // Infinite sequence
return true;
}

@Override
Expand Down

0 comments on commit c190368

Please sign in to comment.