up(n) = (n+1)%3 \\ 0 -> 1 -> 2 -> 0 down(n) = (n-1)%3 \\ 2 -> 1 -> 0 -> 2 is(n) = { \\ /\ \\ v \ t-u-v form an equilateral triangle \\ / \ \\ / u \\ -t------ \\ f(t) = u \\ f(u) = v \\ f(v) = t my (d = digits(n, 3), f, g); if (up(d[1]) == d[#d], f = up, down(d[1]) == d[#d], f = down, \\ d[1] and d[#d] must be different return (0); ); my (r = d); for (k = 1, #d, if (f(d[k]) != r[#r], return (0), d[#d+1-k] != f(r[1]), return (0) ); r = vector(#r-1, k, (-r[k]-r[k+1]) % 3); ); return (1); } \\ compute potential right part for given digits and turning function f right(d, f) = { my (r=vector(#d)); for (k=1, #d, r[#r+1-k] = f(d[1]); d = vector(#d-1, k, (-d[k]-d[k+1])%3); ); return (r); } \\ triangular numbers t(n) = n*(n+1)/2 { my (k = 0, d, c, vv); for (w = 1, oo, forstep (e = 1, 0, -1, \\ we will add w-e digits if (t(2*w-e)%3==0, for (n = 3^(w-1), 3^w-1, d = digits(n, 3); vv = []; for (i = 1, 2, r = right(d, [up, down][i]); c = fromdigits(concat(d, r[1+e..#r]), 3); if (is(c), vv = concat(vv, c); ); ); vv = vecsort(vv); for (i = 1, #vv, print (k++ " " vv[i]); ); ); ); if (k >= 5 000, break (2); ); ); ); }