

In your case, where you generate all previous primes in the process as well, you only have to check if any of the primes in your list, up to sqrt(n), divides n.
#Full list of prime numbers trial
The simplest method is the trial and error: you try if any number between 2 and n-1 divides your candidate prime n.įirst shortcuts are of course a)you only have to check odd numbers, and b)you only hav to check for dividers up to sqrt(n). You need to have the following imports: import fj.P1 If somebody asks for the rest of the stream, call sieve on the rest of the argument stream, filtering out numbers divisible by the first number (the remainder of division is zero).The rest of the return stream is a computation to be produced only when asked for. Assume the first number in the argument stream is prime and put it at the front of the return stream.Stream pltn = primes.takeWhile(naturalOrd.lessThan(n)) You can do things like this: // Take the first n primes Now you have a value, that you can carry around, which is an infinite stream of primes. = sieve(forever(naturalEnumerator, natural(2).some())) public static Stream sieve(final Stream xs) The type Natural is essentially a BigInteger >= 0. Using stream-based programming in Functional Java, I came up with the following. This function generates the first n primes (edit: where n>1), so generatePrimes(5) will return an ArrayList with ).Where(candidate => !cache.TakeWhile(c => c candidate.Current % cachedPrime = 0)) What is the most elegant way to implement this function: ArrayList generatePrimes(int n)
