User blog:QuasarBooster/Arithmetisation of worms!

Consider the following sequence, for any natural number n: \[ W_0(n)=n+1\\ W_k(n)=\begin{cases} \frac{W_{k-1}(n)-1}{n+2}&\text{if}W_{k-1}(n)\mod(n+2)=1\\ (W_{k-1}(n)-1)(n+2)^{dk}+(W_{k-1}(n)\mod(n+2)^{dk}-1)\frac{(n+2)^{dk}-1}{(n+2)^d-1} &\text{otherwise, where}\\ d=\min\left(i:\left\lfloor\frac{W_{k-1}(n)}{(n+2)^i}\right\rfloor\mod(n+2)<W_{k-1}(n)\mod(n+2)\right) \end{cases} \] The sequence is defined to terminate if its terms reach 0. It just so happens that the sequence always terminates regardless of n. It also happens to be that the number of steps before it reaches 0 is exactly equal to Worm(n) (i.e. Beklemishev worms)!

I've been trying to interpret worms as numbers for a long time, so I'm really proud of what I came up with. I wanted the sequence to only involve basic arithmetic but I'll happily grant the use of the floor and mod functions, as they're basic enough. The only bit that I'm not fully satisfied with is the requirement of d, which uses "the minimum blank such that blank" stuff. I tried to get rid of it but haven't succeeded so far. Oh well, I'm still really happy with this.

Here's some code: def worm(n): W=n+1 k=0 while W:   print(W) k+=1 if W%(n+2)==1:W//=(n+2) else: d=1 while W%(n+2)<=W//(n+2)**d%(n+2):d+=1 W=(W-1)*(n+2)**(d*k)+(W%(n+2)**d-1)*((n+2)**(d*k)-1)//((n+2)**d-1) return k Here is the sequence for n=2. Notice that it terminates in 51 steps:
 * 3
 * 10
 * 2457
 * 614
 * 157013
 * 39253
 * 9813
 * 2453
 * 613
 * 153
 * 38
 * 156587349
 * 39146837
 * 9786709
 * 2446677
 * 611669
 * 152917
 * 38229
 * 9557
 * 2389
 * 597
 * 149
 * 37
 * 9
 * 2
 * 1501199875790165
 * 375299968947541
 * 93824992236885
 * 23456248059221
 * 5864062014805
 * 1466015503701
 * 366503875925
 * 91625968981
 * 22906492245
 * 5726623061
 * 1431655765
 * 357913941
 * 89478485
 * 22369621
 * 5592405
 * 1398101
 * 349525
 * 87381
 * 21845
 * 5461
 * 1365
 * 341
 * 85
 * 21
 * 5
 * 1
 * 0