5
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – user9660 Feb 25 '15 at 15:21
  • $\begingroup$ Divisible[n!, n^(2n)] might be a little more explicit than Mod in this case. Also, this will never be true for integers greater than 1: n! is less than n^(2n), and no number can be divisible by a greater number! $\endgroup$ – 2012rcampion Feb 25 '15 at 18:36
  • 1
    $\begingroup$ duplicate Q/A: How to avoid returning a Null if there is no “else” condition in an If contruct with several answers including one by @Mr.Wizard featuring the vanishing function ##&[] as the third argument of If: Table[If[Mod[n!, n^(2 n)] == 0, n, ## &[]], {n, 1, 1000}] $\endgroup$ – kglr Feb 25 '15 at 20:20
7
$\begingroup$
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}

| improve this answer | |
$\endgroup$
  • $\begingroup$ thanks very much for so vast and quick answer $\endgroup$ – mathfan1999 Feb 25 '15 at 21:05
2
$\begingroup$

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.

| improve this answer | |
$\endgroup$
  • $\begingroup$ thank you, I haven't seen Sow / Reap commends before. and I didn't expect a vast reply few minutes after asking question :) $\endgroup$ – mathfan1999 Feb 25 '15 at 21:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.