Generate the sequence number of bases in which n is a palindrome (OEIS A126071).

Specifically, the sequence is defined as follows: given a number n, express it in base a for a = 1,2, ..., n, and count how many of those expressions are palindromic. "Palindromic" is understood in terms of reversing the base-a digits of the expression as atomic units (thanks, @Martin Büttner). As an example, consider n= 5:

  • a=1: the expression is 11111: palindromic
  • a=2: the expression is 101: palindromic
  • a=3: the expression is 12: not palindromic
  • a=4: the expression is 11: palindromic
  • a=5: the expression is 10: not palindromic

Therefore the result for n=5 is 3. Note that OEIS uses bases 2, ..., n+1 instead of 1, ..., n (thanks, @beaker). It's equivalent, because the expressions in base 1 and n+1 are always palindromic.

The first values of the sequence are

 1, 1, 2, 2, 3, 2, 3, 3, 3, 4, 2, 3, 3, 3, 4, 4, 4, 4, 2, 4, 5, ...

Input is a positive integer n. Output is the first n terms of the sequence.

The program should theoretically work (given enough time and memory) for any n up to limitations caused by your default data type in any internal computations.

All functions allowed. Lowest number of bytes wins.

  • \$\begingroup\$ Related \$\endgroup\$ – Luis Mendo Jan 19 '16 at 22:04
  • 1
    \$\begingroup\$ If it's helpful to anyone, it's worth noting that a number n is also always palindromic in base n-1. \$\endgroup\$ – Computronium Aug 31 '17 at 13:43
  • \$\begingroup\$ This is A126071 \$\endgroup\$ – Titus Aug 31 '17 at 18:25

14 Answers 14


Pyth, 13 bytes


The brevity of this is mostly due to the Invaluable "Invariant" command.

msf_ITjLdSdSQ       implicit: Q=input
m         d         map lambda d over
           SQ       Inclusive range 1 to Q
      jLdSd         Convert d to all the bases between 1 and d
  f                  filter lambda T:
   _IT                 is invariant under reverse
 l                  number that are invariant under reverse

If True is an acceptable output for 1, msm_IjdkSdSQ (12 bytes) works.

Try it here.

| improve this answer | |

Jelly, 14 bytes


Try it online!

Non-competing version

The Jelly interpreter had a bug that made converting to unary impossible. This has been fixed now, so the following code (12 bytes) also accomplishes the task at hand.


Try it online!

How it works

bR‘$µ=UP€S  Helper link. Argument: z

 R‘$        Apply range and increment, i.e., map z to [2, ..., z + 1].
            In the non-competing version R simply maps z to [1, ... z].
b           Convert z to each of the bases to the right.
    µ       Begin a new, monadic chain. Argument: base conversions
     =U     Compare the digits of each base with the reversed digits.
            = has depth 0, so [1,2,3]=[1,3,3] yields [1,0,1].
       P€   Take the product of the innermost arrays.
         S  Sum all resulting Booleans.

RÇ€         Main link. Argument: n

R           Yield [1, ..., n].
 ǀ         Apply the helper link to each.
| improve this answer | |

MATL, 19 20 bytes


Uses current release (10.1.0), which is earlier than this challenge.

Try it online!


:            % vector [1,2,...,N], where "N" is implicit input
"            % for each number in that vector
  0          % push 0
  @          % push number 1,2,...N corresponding to current iteration, say "n" 
  XK         % copy n to clipboard
  :Q         % vector [2,3,...,n+1]
  "          % for each number "m" in that vector
    K        % push n
    @:       % vector [1,2,...,m]
    YA       % express n in base m with symbols 1,2,...,m
    tP       % duplicate and permute
    =A       % 1 if all entries are equal (palindrome), 0 otherwise
    +        % add that number
             % implicitly close the two loops and display stack contents
| improve this answer | |

CJam, 20 bytes


Test it here.

| improve this answer | |

Haskell, 88 bytes

a!b|a<b=[a]|1>0=mod a b:(div a b)!b
f n=[1+sum[1|x<-[2..y],y!x==reverse(y!x)]|y<-[1..n]]
| improve this answer | |

ES6, 149 bytes


Works for bases > 36 too.

| improve this answer | |

JavaScript (ES6), 105 95 bytes



Takes a number from 1 to 36 (the limitation of base conversion in JavaScript) and returns an array of the sequence.

Recursive function that checks for palindromes when a base is passed, else returns the sequence if just n is passed.


  // Base palindrome checking
    b<3?1:                 // return 1 for base-1, since toString(2)
    f(n,b-1)+(             // return the sum of all lower bases and check  this
      [...s=n.toString(b)] // s = n in base b
      .reverse().join``==s // add 1 if it is a palindrome

  // Sequence generation
    n<2?[1]:               // return 1 for the first value of the sequence
    [...f(n-1),f(n,n)]     // return the value for n after the previous values


var solution = f=(n,b)=>b?b<2?1:f(n,b-1)+([...s=n.toString(b)].reverse().join``==s):n<2?[1]:[...f(n-1),f(n,n)]
<input type="number" oninput="result.textContent=solution(+this.value)" />
<pre id="result"></pre>

| improve this answer | |
  • \$\begingroup\$ Is there a way to turn that into a recursive function? I feel like that could save some bytes. \$\endgroup\$ – Mama Fun Roll Jan 24 '16 at 6:05
  • \$\begingroup\$ @ՊՓԼՃՐՊՃՈԲՍԼ You're right. Thanks for the tip. \$\endgroup\$ – user81655 Jan 25 '16 at 14:23

Jelly, 8 bytes


Try it online!

Possibly non-competing version:


Try it online!

| improve this answer | |

PHP, 73+1 bytes


works for bases 1 to 36. Run as pipe with -nR or try it online.

| improve this answer | |

PHP, 92+1 bytes:


works for all bases. Run as pipe with -nR or try it online.

| improve this answer | |

Python 2, 97 bytes

for b in range(2,n):
	while z:a+=[z%b];z//=b
print c

My first Python post, actually my first Python code at all
probably has some golfing potential.

Try it online!

| improve this answer | |

><>, 197+2 Bytes

+2 for -v flag

:1+0v    ;n\
1\  \$:@2(?/
\   \~0${:}
~~1 \  \
 \  /@@r/!?/
~$/       \-1

tio.run doesn't seem to return any output for n>1, but you can verify it on https://fishlanguage.com. Input goes in the "Initial stack" box.

| improve this answer | |

Japt, 10 bytes

õ_õ!ìZ èêS

Try it


õ              :Range [1,input]
 _             :Map each Z
  õ            :  Range [1,Z] (let's call each X)
   !ìZ         :   Convert Z to a base X digit array
       è       :  Count
        êS     :   Palindromes
| improve this answer | |

Python 2, 85 bytes

def f(a):b,c=2,0;exec'd,m=[],a\nwhile m:d+=[m%b];m/=b\nc+=d[::-1]==d;b+=1;'*a;print c

Try it online!

Expects an integer as an argument.


# named function
def f(a):
    # initialize variable to track base (b) and to track palindromes (c)
        # construct code
        # initialize variable to store remainders (m) and to track divisor (d)
        # while d is not zero,
        # add the current remainder to the array
        # and divide d by the base and assign the result back to d
        while d:m+=[m%b];d/=b
        # False == 0 and True == 1, so add 1 to total if m == reversed(m)
        # increment base
        # terminate with ; so that next statement can be executed separately
    # execute constructed statement (a) times
    # print result
    print c
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.