OFFSET
0,3
COMMENTS
From Yosu Yurramendi, Mar 21 2017: (Start)
This sequence is a self-inverse permutation of the integers. Except for fixed points 0, 1, it consists completely of 2-cycles: (2^(m+1)+k, 2^(m+1)+2^m+k), m >= 0, 0 <= k < 2^m.
LINKS
Yosu Yurramendi, Table of n, a(n) for n = 0..32767
FORMULA
If 2*2^k <= n < 3*2^k then a(n) = n + 2^k; if 3*2^k <= n < 4*2^k then a(n) = n - 2^k.
a(0)=0, a(1)=1, a(2)=3, a(3) = 2, a(2n) = 2*a(n), a(2n+1) = 2*a(n) + 1. - Ralf Stephan, Aug 23 2003
EXAMPLE
a(11)=15 since 11 is written in binary as 1011, which changes to 1111, i.e., 15; a(12)=8 since 12 is written as 1100 which changes to 1000, i.e., 8.
MAPLE
a:= proc(n) option remember;
if n<2 then n
elif n<4 then 5-n
elif `mod`(n, 2)=0 then 2*a(n/2)
else 2*a((n-1)/2) + 1
fi; end proc;
seq(a(n), n = 0..80); # G. C. Greubel, Dec 08 2019
MATHEMATICA
bc[n_]:=Module[{idn2=IntegerDigits[n, 2]}, If[idn2[[2]]==1, idn2[[2]]=0, idn2[[2]]=1]; FromDigits[idn2, 2]]; Join[{0, 1}, Array[bc, 80, 2]] (* Harvey P. Dale, May 31 2012 *)
a[n_]:= a[n]= If[n<2, n, If[n<4, 5-n, If[EvenQ[n], 2*a[n/2], 2*a[(n-1)/2] +1]]]; Table[a[n], {n, 0, 80}] (* G. C. Greubel, Dec 08 2019 *)
PROG
(PARI) a(n)=if(n<2, n>0, 3/2*2^floor(log(n)/log(2))-2^floor(log(4/3*n)/log(2))+n) /* Ralf Stephan */
(PARI) a(n) = if(n<2, n, bitxor(n, 1<<(logint(n, 2)-1))); \\ Kevin Ryde, Apr 09 2020
(Python)
import math
def a(n): return n if n<2 else 3/2*2**int(math.floor(math.log(n)/math.log(2))) - 2**int(math.floor(math.log(4/3*n)/math.log(2))) + n # Indranil Ghosh, Mar 22 2017
(R)
maxrow <- 8 # by choice
b01 <- 1
for(m in 0:(maxrow-1)){
b01 <- c(b01, rep(0, 2^(m+1))); b01[2^(m+1):(2^(m+1)+2^m-1)] <- 1
}
a <- c(1, 3, 2)
for(m in 0:(maxrow-2))
for(k in 0:(2^m-1)){
a[2^(m+2) + k] <- a[2^(m+1) + 2^m + k] + 2^((m+1) + b01[2^(m+2) + k])
a[2^(m+2) + + 2^m + k] <- a[2^(m+1) + k] + 2^((m+1) + b01[2^(m+2) + + 2^m + k])
a[2^(m+2) + 2^(m+1) + k] <- a[2^(m+1) + 2^m + k] + 2^((m+1) + b01[2^(m+2) + 2^(m+1) + k])
a[2^(m+2) + 2^(m+1) + 2^m + k] <- a[2^(m+1) + k] + 2^((m+1) + b01[2^(m+2) + 2^(m+1) + 2^m + k])
}
(a <- c(0, a)) # Yosu Yurramendi, Mar 30 2017
(R)
a <- c(1, 3, 2)
maxn <- 63 # by choice
for(n in 2:maxn){ a[2*n ] <- 2*a[n]
a[2*n+1] <- 2*a[n] + 1 }
(a <- c(0, a)) # Yosu Yurramendi, Nov 12 2019
(Sage)
@CachedFunction
def a(n):
if (n<2): return n
elif (n<4): return 5-n
elif (mod(n, 2)==0): return 2*a(n/2)
else: return 2*a((n-1)/2) + 1
[a(n) for n in (0..80)] # G. C. Greubel, Dec 08 2019
CROSSREFS
KEYWORD
easy,nonn,base
AUTHOR
Henry Bottomley, Sep 03 2001
STATUS
approved