s = 0
unseen = 1
seen(v) = bit test(s, v)
see(v) = s = bit or(s, 2^v); while (seen(unseen), unseen++)

neg(n) = { my (v=0, b=1, t); while (n, t=centerlift(Mod(n, 3)); if (t==-1, v+=b); n=(n-t)\3; b*=2); v }
pos(n) = { my (v=0, b=1, t); while (n, t=centerlift(Mod(n, 3)); if (t==+1, v+=b); n=(n-t)\3; b*=2); v }

ncache = apply(neg, [0..3^9])
pcache = apply(pos, [0..3^9])

neg(n) = ncache[1+n]
pos(n) = pcache[1+n]

other(p) = {
	see(p);
	my (np=neg(p));
	for (v=unseen, oo,
		if (!seen(v) && bitand(pos(v), np)==np,
			return (v);
		);
	);
}

for (n=0, 3^8, print (n " " v=if (n==0, 0, other(v))))

quit