Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Created November 19, 2024 18:30
Show Gist options
  • Save gigamonkey/0d86d842fa13d6376c33f8ac25a34d36 to your computer and use it in GitHub Desktop.
Save gigamonkey/0d86d842fa13d6376c33f8ac25a34d36 to your computer and use it in GitHub Desktop.
Primes impl with streams
import static java.lang.Math.sqrt;
import static java.util.stream.IntStream.range;
import static java.util.stream.IntStream.rangeClosed;
public class Primes {
public boolean isPrime(int n) {
return n > 1 && !rangeClosed(2, (int) sqrt(n)).anyMatch(d -> n % d == 0);
}
public int numberOfPrimesBelow(int limit) {
return (int) range(2, limit).filter(this::isPrime).count();
}
public int numberOfTwinPrimePairsBelow(int limit) {
return (int) range(2, limit)
.filter(n -> isPrime(n) && isPrime(n + 2))
.count();
}
public boolean isSuperPrime(int n) {
return isPrime(n) && isPrime(numberOfPrimesBelow(n) + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment