OFFSET
0,3
COMMENTS
This sequence is a self-inverse permutation of nonnegative integers.
LINKS
Rémy Sigrist, Table of n, a(n) for n = 0..8192
Rémy Sigrist, Colored scatterplot of (n, a(n)) for n = 0..2^18-1 (where the color is function of A005811(n))
FORMULA
EXAMPLE
For n = 150:
- the binary representation of 150 is "10010110",
- we have three runs of ones: "1", "1" and "11",
- we exchange the first and the third run, and the second remains in place,
- we obtain: "11001010",
- hence a(150) = 202.
MATHEMATICA
a[n_] := Module[{s=Split[IntegerDigits[n, 2]]}, m=Length[s]; If[m>1, m2 = m-1 + Mod[m, 2]; ind=Riffle[Range[m2, 1, -2], Range[2, m, 2]]; FromDigits[Flatten[ s[[ind]]], 2], n]]; Array[a, 120, 0] (* Amiram Eldar, Dec 12 2018 *)
PROG
(PARI) a(n) = {
my (r=n, o=[], v=0, p=1, i=0);
while (r, my (l=valuation(r+(r%2), 2)); if (r%2, o=concat(l, o)); r\=2^l);
while (n, my (l=valuation(n+(n%2), 2)); if (n%2, v+=(2^o[i++]-1)*p; p*=2^o[i], p*=2^l); n\=2^l);
return (v);
}
CROSSREFS
KEYWORD
AUTHOR
Rémy Sigrist, Dec 09 2018
STATUS
approved