Java Reference
In-Depth Information
.filter(MyMathUtils::isPrime)
.limit(n);
}
public static boolean isPrime(int candidate) {
int candidateRoot = (int) Math.sqrt((double) candidate);
return IntStream.rangeClosed(2, candidateRoot)
.noneMatch(i -> candidate % i == 0);
}
But this solution is somewhat awkward: you have to iterate through every number every time to
see if it can be exactly divided by a candidate number. (Actually you need only test with numbers
that have been already classified as prime.)
Ideally the stream should filter out numbers divisible by the prime it's producing on the go! This
sounds crazy, so we'll try to sketch out how this might work:
1 . You need a stream of numbers from which you'll select prime numbers.
2 . From that stream you take the first number (the head of the stream), which will be a prime
number (at the initial step this will be 2).
3 . You then filter all the numbers divisible by that number from the tail of the stream.
4 . The resulting tail is the new stream of numbers that you can use to find prime numbers.
Essentially you go back to step 1, so this algorithm is recursive.
Note that this algorithm is “poor” for a few reasons. [ 1 ] But it's simple to reason about algorithms
for the purpose of working with streams. Let's try to write this algorithm using the Streams API.
1 More information about why the algorithm is poor can be found at
www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf .
Step 1: Get a stream of numbers
You can get an infinite stream of numbers starting from 2 using the method IntStream.iterate,
which we described in chapter 5 as follows:
static Intstream numbers(){
return IntStream.iterate(2, n -> n + 1);
}
 
Search WWH ::




Custom Search