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];,

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

  • 3
    $\begingroup$ 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. $\endgroup$
    – C. E.
    Jul 15, 2016 at 15:03
  • $\begingroup$ No, missed that, will try. $\endgroup$
    – Erik Itter
    Jul 15, 2016 at 15:06
  • $\begingroup$ 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... $\endgroup$
    – Erik Itter
    Jul 15, 2016 at 19:31
  • $\begingroup$ no, do not get how to use it with All NestWhileList[step, 222, # > 1 && # < 1000000 &, All] already seems to be an infinite loop $\endgroup$
    – Erik Itter
    Jul 15, 2016 at 19:38
  • 1
    $\begingroup$ 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. $\endgroup$
    – Mr.Wizard
    Jul 16, 2016 at 2:39

1 Answer 1



using the fourth argument of NestWhileList, All

which solves the example with Mr.Wizard:

NestWhileList[step, n, Signature@{1, n, ##2} =!= 0 &, All]
  • $\begingroup$ if this should still not be appropriate how do I need to proceed to mark the question as answered? $\endgroup$
    – Erik Itter
    Jul 16, 2016 at 15:29
  • $\begingroup$ you deleted my answere, that I put there to mark it as answered refering to the answers provided as comments. $\endgroup$
    – Erik Itter
    Jul 16, 2016 at 15:31
  • $\begingroup$ As I said, your previous post was not an answer in any way. This one is much better. (In any event, see this meta thread.) $\endgroup$ Jul 16, 2016 at 15:32

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.