Skip to main content
1 of 4
Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k

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, and reaping only the tags that you want. (True in the example below.) This silently discards the results that do not match.

test = Divisible[#, 1*^6] &;

Reap[Do[Sow[i, test @ i], {i, 1*^7}], True][[2, 1]]

(* Out= *)
{1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000}

Note that only a small amount of memory us 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 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 is about five and a half times faster than the first method on my system.

Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k