1
$\begingroup$

I have 3 lines of code that does the Collatz Conjecture in mathematica. the code is the following:

ClearAll[collatz];
collatz[1] = 1;
collatz[n_ /; EvenQ[n]] := (Sow[n]; collatz[n/2])
collatz[n_ /; OddQ[n]] := (Sow[n]; collatz[3 n + 1])
runcoll[n_] := Reap[collatz[n]]

this code performs until 1 is reached but I want to have the code done a specificities cnumber of times, say 10. how can I write a loop that perform this only a specific number of times?

and this has not happed btw:

 ClearAll[collatz];
    collatz[1] = 1;
n=1; While [n<11,
    collatz[n_ /; EvenQ[n]] := (Sow[n]; collatz[n/2])
    collatz[n_ /; OddQ[n]] := (Sow[n]; collatz[3 n + 1])
    runcoll[n_] := Reap[collatz[n]]
; n++]
$\endgroup$
2
$\begingroup$

You can use a counter like this:

ClearAll[collatz];
collatz[1] = 1;
collatz[n_ /; EvenQ[n], i_ /; i < 10] := (Sow[n]; collatz[n/2, i + 1])
collatz[n_ /; OddQ[n], i_ /; i < 10] := (Sow[n]; collatz[3 n + 1, i + 1])
collatz[n_, i_ /; i >= 10] := n
runcoll[n_] := Reap[collatz[n, 0]]

runcoll[100]

{22, {{100, 50, 25, 76, 38, 19, 58, 29, 88, 44}}}

The recursive functions only apply while $i < 10$ because of the condition specified with the /; syntax. When $i$ is larger than that and $n$ is not $1$, then the only definition that applies is a definition that returns $n$, thus ending the recursive chain.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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