Java Reference
In-Depth Information
// Checks if the specified nubmer is a prime number
public static boolean isPrime(long number) {
// <= 1 is not a prime number
if (number <= 1) {
return false;
}
// 2 is a prime number
if (number == 2) {
return true;
}
// Even numbers > 2 are not prime numbers
if (number % 2 == 0) {
return false;
}
long maxDivisor = (long) Math.sqrt(number);
for (int counter = 3; counter <= maxDivisor; counter += 2) {
if (number % counter == 0) {
return false;
}
}
return true;
}
}
The following snippet of code creates an infinite stream of prime numbers and prints the first five prime numbers
on the standard output:
Stream.iterate(2L, PrimeUtil::next)
.limit(5)
.forEach(System.out::println);
2
3
5
7
11
There is another way to get the first five prime numbers. You can generate an infinite stream of natural numbers,
apply a filter operation to pick only the prime numbers, and limit the filtered stream to five. The following snippet of
code shows this logic using the isPrime() method of the PrimeUtil class:
// Print the first 5 prime numbers
Stream.iterate(2L, n -> n + 1)
.filter(PrimeUtil::isPrime)
.limit(5)
.forEach(System.out::println);
Search WWH ::




Custom Search