# How to stop Nest when the next element is already in the list

step[n_] :=
step[n] = Plus @@ Delete[Divisors[n], Length[Divisors[n]]];

maxLength = 0;
For[n = 220, n < 223, n++,
chain = NestWhileList[step, n, # > 1 && # < 1000000 &];
chain = Delete[chain, Length[chain]];
If[Length[chain] > maxLength,
maxLength = Length[chain];
bestN = Min[chain];,
Nothing[]
]
]

does not work, I guess because n=220 indeed produces an infinite List (am1c4ble cha1n) which ist precisely what I am looking for. But how do I test for that, so how do I add && # is not part of chain already?

Or am I assuming what the problem is incorrectly? Working test for example with n=221, n<223 terminating and having the correct chain

• Have you considered using the fourth argument of NestWhileList, All? This would supply you with the information you need to check if # has appeared previously. Jul 15, 2016 at 15:03
• No, missed that, will try. Jul 15, 2016 at 15:06
• obviously, just did not mention it in order to not index it in search engines - also I beblieve the p0j3ct 3u13r is to sensitive about that. Who wants to cheat ... have at it... Jul 15, 2016 at 19:31
• no, do not get how to use it with All NestWhileList[step, 222, # > 1 && # < 1000000 &, All] already seems to be an infinite loop Jul 15, 2016 at 19:38
• A single piece of my solution from six years ago: NestWhileList[ds, n, Signature@{1, n, ##2} =!= 0 &, All] where ds is similar to your step. I used Signature to check for duplicates. One could also make use of UnsameQ or the new-in-10 DuplicateFreeQ with different performance profiles. (6745) I'll leave the rest for you to figure out. Jul 16, 2016 at 2:39