The Collatz Conjecture in a Spreadsheet | Introduction to Recursive LAMBDA()
Channel: Chris Armstrong
Date: 2023-03-09

The Collatz conjecture states that if a number is even, we divide it by two, and if it is odd, we multiply by three and add one, and then if this continues, it should always reach 1. This has been tested to obscenely high numbers by professionals. Yet the mathematical proof that this is always true is, so far, frustratingly outside of modern mathematics. No, we can't do that in Excel. Or, at least, I don't want to. Come on...

Anyway... because this process recurs, it's possible to use a recursive LAMBDA() function to test numbers, so it makes for a good tutorial on recursive lambda functions -- where the function calls itself a certain number of times in a loop.

The important thing is to set a way to escape your function, either by a condition or some kind of time-out.

The full thing to put into the name manager, named "collatz", is:
=LAMBDA(input,i,limit,IF(i=limit,"timed out after "&i,IF(input=1,"reached 1 after "&i&" iterations",collatz(IF(ISEVEN(+input),input/2,3*input+1),i+1,limit))))

It's not elegant or intuitive, which leads me to believe that recursive lambda functions in Excel are more of a hack than a design feature, but it mostly works.