You can use limit(int) : you will need to determine how many elements will be between 3 and sqrt(n) in step 2. There is exactly (sqrt(n) - 3) / 2 + 1 , so you can write:
IntStream.iterate(3, i -> i + 2).limit((int) (Math.sqrt(n) - 3) / 2 + 1);
Having said that, you can also create a closed range from 3 to sqrt(n) and filter out even values, for example:
IntStream.rangeClosed(3, (int) Math.sqrt(n)).filter(i -> i % 2 > 0)
source share