Numbers that can be negated by reading backwards

Balanced ternary is a modified version of ternary (base 3), using the three digits 1,0 and -1 (written as T) to represent numbers.

The balanced ternary representation of -n can be obtained by replacing 1 with T and T with 1 in the balanced ternary representation of n.

Examples:

1     // decimal: 1
T     // decimal: -1
1T    // decimal: 3-1 = 2
T1    // decimal: -3+1 = -2
1TTT0 // decimal: 3^4-3^3-3^2-3^1+0= 42


Your task is to write a function or program that outputs all positive integers n for which reversing the balanced ternary representation gives the balanced ternary representation of -n (OEIS 233571).

Example:

1100T0100TT (decimal 78080) reversed is TT0010T0011 (decimal -78080)

The first few numbers in the sequence:

1 -> 2  // balanced ternary: 1T
2 -> 8  // balanced ternary: 10T
3 -> 20 // balanced ternary: 1T1T
4 -> 26 // balanced ternary: 100T
5 -> 32 // balanced ternary: 11TT
6 -> 56 // balanced ternary: 1T01T
...
100 -> 14600 //  balanced ternary: 1T1T001T1T
...
9999 -> 132258878 // balanced ternary: 1001T00TT11001T00T


Rules

• The standard sequence I/O rules apply
• It is allowed to output numbers in balanced ternary:
(as a string using three distinguishable characters, or as a list of digits)
• Your code should be able to handle at least the first 10000 elements of this sequence
• This is so the shortest solution (in each language) measured in bytes wins
• Related: Balanced ternary converter
– xnor
Jul 18, 2023 at 20:41
• Nice first challenge, BTW! Jul 19, 2023 at 11:45
• @Arnauld Thank you. Jul 19, 2023 at 13:34

JavaScript (V8), 59 bytes

Prints the sequence infinitely.

for(k=1;v=++k;t+k||print(k))for(t=0;v;v=v/3|0)t=++v%3-1+t*3


Try it online!

How?

We convert $$\k\ge2\$$ to balanced ternary. Each produced digit is immediately used to convert the reversed balanced ternary representation of $$\k\$$ back to a decimal value $$\t\$$. If we end up with $$\k=-t\$$, we print $$\k\$$.

Commented

for(                // outer loop:
v = ++k;          //   increment k and set v = k
//   (this is > 0, so we loop forever)
t + k || print(k) //   after each iteration: print k if t + k = 0
)                   //
for(              //   inner loop:
v;              //     stop when v = 0
v = v / 3 | 0   //     after each iteration: update v to ⌊v/3⌋
)                 //
t =             //     update t:
++v % 3 - 1 + //       increment v and compute the next balanced
//       ternary digit (v mod 3) - 1
t * 3         //       add t * 3


C (gcc), 74 bytes

v;t;main(k){for(;v=++k;t+k||printf("%d ",k))for(t=0;v;v/=3)t=++v%3-1+t*3;}


Try it online!

Python, 86 bytes

f=lambda x:x and[-~x%3]+f(-~x//3)or[]
i=1
while i:
if f(i:=i+1)==f(-i)[::-1]:print(i)


Attempt This Online!

• 90 bytes Jul 19, 2023 at 8:25
• [*f((x:=x+1)//3),x%3] -> [*f(-~x//3),-~x%3] saves three. Jul 19, 2023 at 20:39
• [-~x%3]+f(-~x//3) saves another. Jul 20, 2023 at 3:38

Pyth, 21 bytes

L?b+y/hb3%b3Y.fq_yZy_


Try it online!

Outputs the first n terms of the sequence.

Explanation

L?b+y/hb3%b3Y.fq_yZy_ZQ    # implicitly add ZQ
# implicitly assign Q = eval(input())
L                          # define y(b)
?b                        #   conditional, if b:
y/hb3                  #     y((b+1) / 3)
+     %b3               #     append b % 3
Y              #   else: []
.f       Q    # return the first Q inputs where lambda Z is true
_yZ        #   y(Z) reversed
q           #   equals
y_Z     #   y(-Z)


Charcoal, 27 bytes

Ｎθ1Φ⍘θT01κＦ⊖⊟⮌↨θ³0⮌Φ⍘θ10TκT


Try it online! Link is to verbose version of code. Outputs the nth term of the sequence. Explanation:

Ｎθ


Input n.

1


Start by printing a 1.

Φ⍘θT01κ


Print n in base 3, decrementing all of the digits (so 0 becomes T), but skipping the first digit.

Ｆ⊖⊟⮌↨θ³0


Print a 0 if n's first digit in base 3 is 2.

⮌Φ⍘θ10Tκ


Print n in base 3, again decrementing after skipping the first digit, but then negating and reversing the result.

T


Print a T.

Raku (Perl 6) (rakudo), 69 66 bytes

.&(my&g={1 x?$_&&g(-+^$_ div 3)~$_%3})==g(-$_).flip&&.say for 1..*


Attempt This Online!

05AB1E, 25 bytes

∞ʒD(‚ε[©_#®>D3%s3/ï})}RQ


Outputs the infinite sequence.

Try it online.

Unfortunately 05AB1E rounds towards 0 for integer-division of negative values, unlike Python which always floors. Otherwise [©_#®>D3%s3/ï} could have been [©_#®>3‰R} for -3 bytes by using divmod builtin ‰.
See that it gives the expected result for positive integers, but not for negative ones.

Explanation:

∞              # Push an infinite positive list: [1,2,3,...]
ʒ             # Filter it by:
‚          #  Pair the current value
(           #  with a negative
D            #  copy of that value
ε            #  Map over this [n,-n] pair:
[           #   Start an infinite loop:
©          #    Store the current value in variable ® (without popping)
_         #    Pop and if it's 0:
#        #     Stop the infinite loop
®          #    If not, push ® again
>         #    Increase it by 1
D        #    Duplicate it
3%      #    Modulo-3
s     #    Swap so the value+1 is at the top again
3/   #    Divide by 3
ï  #    Floor (by casting to an integer)
})          #   After the infinite loop: wrap all values on the stack into a list
}           #  After the map: pop and push both lists to the stack
R          #  Reverse the second list
Q         #  Then check if the two lists are the same
# (after which the filtered infinite list is output implicitly as result)


Nekomata, 14 bytes

Ňᵐ{3r~←}1c:↔_=


Attempt This Online!

Outputs the numbers in balanced ternary (as lists of digits).

Nekomata, 16 bytes

Ňᵐ{3r~←}1c:↔_=3b


Attempt This Online!

Outputs the numbers in the usual form.

Ňᵐ{3r~←}1c:↔_=3b
Ň                   Choose a natural number n
ᵐ{    }            Map the following function to the range [0, n)
3r~                  Choose a random number from [0, 3)
←                 Decrement
(These two steps generate any tuple of [-1, 0, 1])
1c          Prepends 1
(This ensures that it is the balanced ternary representation of a positive number)
:         Duplicate
↔        Reverse
_       Negate
=      Check equality
3b    Convert from base 3


ForWhile, 119 bytes

{1:2$4$[2@4;+'[1-:@48+#)1-:@[48#.]2@[1+:@48'-#).10#.4::@1+'$2@[:@2=[0~;$1+::@1+'$]:)2@4+=[3::@~'$@![2:@1+'$]2@3+1'$]1)}


Input: integer n on the stack

Prints the first n numbers of the sequence in balanced ternary with / as symbol for -1

Online Interpreter

Explanation:

Memory:

• cell 2 -> length of first half of number
• cell 3 -> marker if total length is odd
• cells 4ff -> digits of first half of number (from center outwards)
{  \ procedure
1:2$4$  \ store 1 in cells 2 (length) and 4 (start of value)
[                                  \ loop-without pushing the loop-counter
2@4;+'[1-:@48+#)                 \ write the first digits of the number
1-:@[48#.]                       \ write 0 if number has odd length
2@[1+:@48'-#).10#.4              \ write digits reversed and mirrored
::@1+'$2@[:@2=[0~;$1+::@1+'$]:) \ increment number 2@4+=[ \ check for overflow 3::@~'$                        \ flip cell 3
@![2:@1+'$] \ increase length if new length is even 2@3+1'$                        \ set top trit (ternary digit) to 1
]
1)                                 \ go back to start of loop
}


Perl 5, 134 bytes

while(++$n){for$c("",0){$_="T"x$n;s/T/1/;do{($b=reverse)=~y/1T/T1/;print"$_$c$b$/"}while(/(?=[T0]1*$)/g&&substr($_,pos)=~y/T01/01T/)}}  Like some other answers, it uses string manipulations only, no math, to produce the reflected pattern of the sequence elements. • while (++$n) : Loop over increasing length of the prefix, endlessly.
• for $c ("",0) : Do all the following twice, once with an empty string for the "center" and once with digit "0" for the "center". • $_ = "T" x $n; s/T/1/; : Form the smallest positive value of length $n, by creating a string of "T" characters then changing its first character to "1".
• do...
• ($b = reverse) =~ y/1T/T1/; : Form the suffix by reversing the prefix then negating its digits. • print "$_$c$b$/" : Print the full output: prefix, center, suffix, and newline. • while (/(?=[T0]1*$)/g && substr(\$_, pos) =~ y/T01/01T/) : Increment the prefix as a ternary string. Find the position of the last digit which is not a "1". The loop ends if the string is nothing but "1" digits. Otherwise, change the digit found from "T" to "0" or from "0" to "1", and change all the following "1" digits (if any) to "T" digits.

Try it online!

Jelly, 15 bytes

b3’µḢR¬;ṚN⁸;Ø+j


A monadic Link that accepts a positive integer, $$\n\$$, and yields the $$\n^{\text{th}}\$$ reverse-negate-invariant number in balanced ternary as a list of integers from $$\\{-1,0,1\}\$$.

Try it online! Or see the test-suite (first 100 converted to integers).

How?

b3’µḢR¬;ṚN⁸;Ø+j - Link: positive integer, n            e.g. 21
b3              - convert {n} to base three                 [2,1,0]
’             - decrement {each digit}                D = [1,0,-1]
µ            - start a new monadic chain - f(D=that)
Ḣ           - pop the head off {D} and yield it         1  (and D -> [0,-1])
R          - range {that} (1 -> [1] else [])           [1]
¬         - logical NOT {that} ([] -> []; [1] -> [0]) [0]
Ṛ       - reverse {modified D}                      [-1,0]
;        - concatenate                               [0,-1,0]
N      - negate {that}                             [0,1,0]
⁸     - chain's left argument -> modified D       [0,-1]
;    - concatenate                               [0,-1,0,1,0]
Ø+  - signs literal -> [1,-1]                   [1,-1]
j - join                                      [1,0,-1,0,1,0,-1]
`