A081134 Distance to nearest power of 3.
0, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7
Offset: 1
Examples
a(7) = 2 since 9 is closest power of 3 to 7 and 9 - 7 = 2.
Links
- Rémy Sigrist, Table of n, a(n) for n = 1..10000
- Klaus Brockhaus, Illustration for A081134, A081249, A081250 and A081251
- Hsien-Kuei Hwang, S. Janson, and T.-H. Tsai, Exact and asymptotic solutions of the recurrence f(n) = f(floor(n/2)) + f(ceiling(n/2)) + g(n): theory and applications, Preprint 2016.
- Hsien-Kuei Hwang, S. Janson, and T.-H. Tsai, Exact and Asymptotic Solutions of a Divide-and-Conquer Recurrence Dividing at Half: Theory and Applications, ACM Transactions on Algorithms, 13:4 (2017), #47; DOI: 10.1145/3127585.
- Index entries for sequences related to distance to nearest element of some set
Programs
-
Maple
a:= n-> (h-> min(n-h, 3*h-n))(3^ilog[3](n)): seq(a(n), n=1..100); # Alois P. Heinz, Mar 28 2021
-
Mathematica
Flatten[Table[Join[Range[0,3^n],Range[3^n-1,1,-1]],{n,0,4}]] (* Harvey P. Dale, Dec 31 2013 *)
-
PARI
a(n) = my (p=#digits(n,3)); return (min(n-3^(p-1), 3^p-n)) \\ Rémy Sigrist, Mar 24 2018
-
Python
def A081134(n): kmin, kmax = 0,1 while 3**kmax <= n: kmax *= 2 while True: kmid = (kmax+kmin)//2 if 3**kmid > n: kmax = kmid else: kmin = kmid if kmax-kmin <= 1: break return min(n-3**kmin, 3*3**kmin-n) # Chai Wah Wu, Mar 31 2021
Formula
a(n) = min(n-3^floor(log(n)/log(3)), 3*3^floor(log(n)/log(3))-n).
From Peter Bala, Sep 30 2022: (Start)
a(1) = 0, a(2) = 1, a(3) = 0; thereafter, a(3*n) = 3*a(n), a(3*n+1) = 2*a(n) + a(n+1) and a(3*n+2) = a(n) + 2*a(n+1). (End)