0
$\begingroup$

I am using the below command in Mathematica (an example):

Catch[Do[i; If[EulerPhi[i] > EulerPhi[i + 1], Print[i]], {i, 1, 100}]]

Of course, I would like to do this for other functions (maybe) and for 100 replaced for much bigger numbers.

How to count the number of outputs (printed solutions) for this? Since they appear in a column, I cannot use count commands for table. At least, they are not working for me.

$\endgroup$
4
  • $\begingroup$ Use Table instead of Do and use Nothing as the 3rd arg to If. And just use i, not Print in the 2nd arg. $\endgroup$
    – Michael E2
    Commented Feb 10, 2020 at 2:09
  • 1
    $\begingroup$ @MichaelE2 I dind't understand. In fact, I think it didn't work. Could you please write it up here? $\endgroup$
    – Jean
    Commented Feb 10, 2020 at 2:36
  • 1
    $\begingroup$ @Jean, I guess, that Michael E2 means something like this Length@Table[If[EulerPhi[i] > EulerPhi[i + 1], i, Nothing], {i, 1, 100}]. The output of Table can be counted very easy.. $\endgroup$
    – Rom38
    Commented Feb 10, 2020 at 5:01
  • $\begingroup$ Sorry I am busy. @Rom38 is right. Tho if counting is all that is needed you cold use cnt=0; Do[If[..., ++cnt], { I, 100}]; cnt $\endgroup$
    – Michael E2
    Commented Feb 10, 2020 at 13:48

2 Answers 2

4
$\begingroup$

You can use Sow and Reap instad of Catch.

Do[ If[EulerPhi[i] > EulerPhi[i + 1], Print@Sow@i]
    , {i, 1, 100}] // 
Reap // Last // Last // Length

https://reference.wolfram.com/language/tutorial/CollectingExpressionsDuringEvaluation.html

$\endgroup$
2
$\begingroup$

Alternative ways to use Reap/Sow

  1. with Scan:
Reap[Scan[Sow[#, EulerPhi[#] > EulerPhi[# + 1]]&, Range@100], True, Length@#2&][[2, 1]]

47

  1. with Do:

Reap[Do[Sow[i, EulerPhi[i] > EulerPhi[i + 1]], {i, 100}], True, Length@#2&][[2, 1]]

47

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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