7

I'm a math enthusiast and I'm looking for examples of rare divisibilities, let's look at the following one:

Table[If[Mod[n!, n^(2 n)] == 0, Print[n]], {n, 1, 1000}]

Here n=1 is the only result and I have 999 Null's.

What should I do to avoid getting large output, where thousands of results are Null's? I mean I would like Mathematica producing a result if occurs, else completely nothing. In the example above, I would like to get "1" only, without the rest of output, where are 999 Null's.

I tried this:

Table[If[Mod[n!, n^(2 n)] == 0, Print[n],{}], {n, 1, 1000}]

But it only replaces Null by {}.

Thanks in advance.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
mathfan1999
  • 73
  • 1
  • 1
  • 4

2 Answers2

10
Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}] /. Null -> Sequence[]

{1}

Cases[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], _?NumericQ]

{1}

Select[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], 
 NumericQ[#] &]

{1}

DeleteCases[Table[If[Mod[n!, n^(2 n)] == 0, n], {n, 1, 1000}], Null]

{1}

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
2

Without comment on whether this is the best solution for your paticular problem, this can be achieved by the following pattern:

Table[
    If[condition, value, Unevaluated@Sequence[]],
    ...
]

Nulls will stay, Sequence[]s will disappear.

For large problems this may be better:

Reap@Do[
    If[condition, Sow[value]],
    ...
]

Check Sow/Reap in the documentation.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • thank you, I haven't seen Sow / Reap commends before. and I didn't expect a vast reply few minutes after asking question :) – mathfan1999 Feb 25 '15 at 21:10