Skip to content

Instantly share code, notes, and snippets.

@mcalavera81
Created October 30, 2015 15:44
Show Gist options
  • Save mcalavera81/53b8a802674c40844243 to your computer and use it in GitHub Desktop.
Save mcalavera81/53b8a802674c40844243 to your computer and use it in GitHub Desktop.
Infinite stream of prime numbers
package com.example;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class MessingAround {
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println(primes(10,10));
}
public static List<Integer> primes(final int fromNumber, final int count) {
return Stream.iterate(primeAfter(fromNumber - 1), MessingAround::primeAfter)
.limit(count).collect(Collectors.<Integer>toList());
}
private static int primeAfter(final int number) {
if (isPrime(number + 1)) return number + 1;
else
return primeAfter(number + 1);
}
public static boolean isPrime(final int number) {
return number > 1 &&
IntStream.rangeClosed(2, (int) Math.sqrt(number)).noneMatch(divisor -> number % divisor == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment