Message Boards Message Boards

0
|
3514 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:
GROUPS:

How can I use NestWhile and NestWhileList

Posted 9 years ago

Hello, I cannot find the good way to achieve the (simple ?) following algorithm. In the Collatz series ,I would obtain : the series of terms,with the first given, the number of terms before the number 1 is reached, the maximal term, and the rank of this term in the series. I could do that with elementary coding systems (quasi pseudo-codes !) but I cannot find my way with Mathematica. I cannot easily translate the logical operations into Mathematica primitives. (For the maximal term and his rank ,as well as for the length of the series ,no problem) Hereafter, I wrote the function f that is to be nested. But this series I would want to interrupt as soon as 1 ist obtained and I do not know how to use NestWhileList associated with MemberQ ;

f[n_Integer] := f[n] = If[EvenQ[n], n/2, 3 n + 1]   or f = If[EvenQ[#], #/2, 3 # + 1] &

NestList[f, 7, 18]
{7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2}

contains of course infinite repeated terms {4,2,1}

NestList[f, 7, 16]
{7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}

is what I would obtain, namely let the calculations stop after 1.

Thank You for help and suggestions.

POSTED BY: Richard KAUSCH
2 Replies
Posted 9 years ago

Thanks,Bill.

Of course,I had tried #>1& but I made a mistake or a misunderstanding of the Documentation : To obtain the whole series ,I added "All" as a fourth argument and the result was the impossibilty of executing the code and I let the computation abort. I will return to the Wolfram Documentation because this All looks either useless or misunderstood by me.

Thank you for your post.

POSTED BY: Richard KAUSCH
Posted 9 years ago

Hint: Try

#>1&

as the third argument to NestWhileList.

Study that until you understand what it does and why.

That should be enough.

POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract