OFFSET
0,4
COMMENTS
Equivalently, a(n) is obtained by swapping the first pair of adjacent bits equal to "10", if such a pair exists. [Here the first pair means the first pair from the right, the least significant end of binary expansion. Comment clarified by Antti Karttunen, Feb 20 2015.]
The fixed point of a(n) is equal to 2^k - 1, where k = A000120(n). In other words, applying a(n) repeatedly packs all the bits to the right.
a(n) is related to the "bubble sort" algorithm. If an array of elements from two classes is encoded in a binary number, a(n) is the first intermediate result that will be obtained when starting a bubble sort from n.
LINKS
Philippe Beaudoin, Table of n, a(n) for n = 0..9999
FORMULA
a(0) = 0; a(2n+1) = 1+2*a(n), a(4n) = 2*a(2n), a(4n+2) = 4n+1. - Antti Karttunen, Feb 21 2015
EXAMPLE
If n = 5 = 101_2 then a(n) = 011_2 = 3.
If n = 8 = 1000_2 then a(8) = 0100_2 = 4.
PROG
(Python)
def bitswap(n):
..# Find first bit = 0.
..m = n
..i = 0
..while (m > 0):
....if m % 2 == 0:
......break
....m = m >> 1
....i = i + 1
..if m == 0:
.....return n
..# Find first bit = 1 following that 0.
..while (m > 0):
....if m % 2 == 1:
......break
....m = m >> 1
....i = i + 1
..# Swap
..return n & ~(1 << i) | (1 << (i-1))
(Haskell)
a241816 n = f (a030308_row n) [] where
f [] _ = n
f (0 : 1 : us) vs = foldr (\b y -> 2 * y + b) 0 $
reverse vs ++ 1 : 0 : us
f (u : us) vs = f us (u : vs)
-- Reinhard Zumkeller, Sep 03 2014
(Python)
def A241816(n):
....s = bin(n)[2:]
....for i in range(len(s)-2, -1, -1):
........if s[i:i+2] == '10':
............return int(s[:i]+'01'+s[i+2:], 2)
....else:
........return n
# Chai Wah Wu, Sep 05 2014
(Scheme, with memoization-macro definec)
(definec (A241816 n) (cond ((zero? n) n) ((odd? n) (+ 1 (* 2 (A241816 (/ (- n 1) 2))))) ((zero? (modulo n 4)) (* 2 (A241816 (/ n 2)))) (else (- n 1))))
;; Antti Karttunen, Feb 21 2015
CROSSREFS
KEYWORD
nonn,base
AUTHOR
Philippe Beaudoin, Aug 19 2014
EXTENSIONS
Definition clarified by Chai Wah Wu, Sep 05 2014
STATUS
approved