I am assuming that EvenQ
is merely an example; clearly if you can generate these values directly, e.g. Range[2, 20, 2]
that will always be preferable.
You can do this reasonably efficiently in terms of both syntax and memory by using Sow
and Reap
:
test = Divisible[#, 1*^6] &;
Reap[Do[If[test @ i, Sow @ i], {i, 1*^6}]][[2, 1]]
(* Out= *)
{1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000}
Note that only a small amount of memory is used, unlike the Table
and Select
method:
MaxMemoryUsed[]
15467904
If you need greater performance you might make use of a block-based approach as I did for Iterate until condition is metIterate until condition is met, e.g.
block = 100000;
Join @@ Table[Select[Range[n block + 1, (n + 1) block], test], {n, 0, 99}]
(* Out= *)
{1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000}
This a bit faster than the first method on my system.