wait, what is this
so there's this math problem from the 1930s called the collatz conjecture, and it's famous cuz it looks like a homework question and nobody can solve it. the rule is stupidly simple: pick any positive number. if it's even, halve it. if it's odd, multiply by 3 and add 1. now do it again to whatever you got. and again. and again.
every single number anyone has ever tried (and people have checked past 268, that's a number with 20 digits) eventually collapses down to 1. every one. but nobody can prove that ALL numbers do. that's the whole conjecture, and it's been open for like 90 years. a guy named paul erdos said "mathematics may not be ready for such problems" lol.
this page lets you play with it three ways: trace one number and watch it bounce, scan thousands of numbers to find the weird ones, and draw all the paths at once to grow a coral. scroll down to the bottom to see how each part is actually built, it's tiny.
one number
the champions
the coral
how it's actually built (the whole thing is tiny)
the rule is the entire algorithm. this is it, six lines, no trick underneath:
function collatz(n){
const seq=[n];
while(n!==1){ n = n%2===0 ? n/2 : 3*n+1; seq.push(n); }
return seq;
}
that's what makes the problem so annoying (in a good way). a rule this dumb produces paths nobody can predict.
the memoization trick (why the scan is fast)
scanning 10,000 numbers naively means walking 10,000 full paths, and some are hundreds of steps. but here's the thing: once a path lands on a number we've already solved, we can stop, cuz the rest is just a lookup. most paths hit a known number within a few steps. so we cache every number we ever solve:
const stepCache=new Map([[1,0]]);
function stepsTo1(n){
const path=[];
// walk until we hit something we already know
while(!stepCache.has(n)){ path.push(n); n = n%2===0 ? n/2 : 3*n+1; }
// then walk BACK up the path we just took, filling in answers
let s=stepCache.get(n);
for(let i=path.length-1;i>=0;i--){ s++; stepCache.set(path[i],s); }
return stepCache.get(path[0]);
}
with this, 10,000 numbers scan in about 10 milliseconds and a million in under a second. fun fact i didn't expect: scanning up to 10,000 caches over 21,000 numbers, more than double, cuz the paths wander way above the limit before coming down and every number they touch gets remembered.
the coral (turtle drawing)
reverse each sequence so it starts at 1, then at every step nudge the heading left for even and right for odd, and draw a short line in the new direction. odd turns are a bit sharper than even ones, otherwise you just get a boring fan. that asymmetry is the entire secret of the shape:
a += seq[i]%2===0 ? evenTurn : oddTurn; x += Math.cos(a)*stepLen; y += Math.sin(a)*stepLen;
everything on this page is one html file with no libraries, no build step, and nothing to install. the source is on github, and there's a notes.md in the repo with the bugs i hit and the numbers i measured while making it.