Using lambdas you can use multithread easily, it should improve your results:
IntStream.rangeClosed(3, x).parallel().filter(n -> n%3 == 0).count()
or, in case you need long values:
LongStream.rangeClosed(3L, x).parallel().filter(n -> n%3L == 0L).count()
I tested it with the following example:
public static void main(String[] args) {
Instant start, end;
long x = 24923869024L;
long count = 0;
// normal loop
start = Instant.now();
for (long n=3L; n<=x; n++) {
if (n%3L==0L) count++;
}
end = Instant.now();
System.out.println("method 1, result = "+count+", time = "+Duration.between(start, end));
// non-parallel stream
start = Instant.now();
count = LongStream.rangeClosed(3L, x).filter(n -> n%3L == 0L).count();
end = Instant.now();
System.out.println("method 2, result = "+count+", time = "+Duration.between(start, end));
// parallel stream
start = Instant.now();
count = LongStream.rangeClosed(3L, x).parallel().filter(n -> n%3L == 0L).count();
end = Instant.now();
System.out.println("method 3, result = "+count+", time = "+Duration.between(start, end));
}
with the results:
method 1, result = 8307956341, time = PT33.55S
method 2, result = 8307956341, time = PT40.611S
method 3, result = 8307956341, time = PT12.637S
```
IntStream.iterate(3, i -> i+3)
\$\endgroup\$