Created
November 19, 2024 18:30
-
-
Save gigamonkey/0d86d842fa13d6376c33f8ac25a34d36 to your computer and use it in GitHub Desktop.
Primes impl with streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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