# Divide them all [duplicate]

A Math.SE user have a funny game explained as such:

1. Pick a random positive integer X.

2. Add +1, 0, -1 to make it divisible by 3Keep track of how much you've added and subtracted. That is your "score"..

3. Divide by 3 to create a new X.

4. Repeat steps 2 and 3 until you reach one.

I'm expecting the shortest code to give the correct score and the decomposition (as a list of the following values [+1;0;-1]) given an integer input.

Input => Expected score => Expected decomposition #explanation
12 => -1 => 0-1 #(12/3 => (4 - 1) / 3 = 1
^^^
25 => 0 => -1+10  (25 - 1) / 3 => (8 + 1) / 3 => (3 + 0) / 3 => 1
^^^            ^^^            ^^^

9320 => -1 => +1+1-10-1+1-1-1 #(9320 + 1) / 3 => (3107 + 1) / 3 => (1036 - 1) / 3 => (345 + 0) /3 => (115 - 1) / 3 => (38 + 1) / 3 => (13 - 1) / 3 => (4 - 1) / 3
^^^               ^^^               ^^^              ^^^             ^^^             ^^^             ^^^            ^^^

• Related. (This challenge basically asks for the sum of digits of the balanced ternary representation.) May 28, 2018 at 14:25
• @MartinEnder it even sounds like a dup... I should enlarge my vocabulary in order to find them more easily. Thanks. May 28, 2018 at 14:33
• I personally don't think it's a dupe because the expected output isn't the bal-ternary representation so you still have to do a slightly different task. Very related though, I agree. May 28, 2018 at 14:46
• @HyperNeutrino, asking for the decomposition and its sum is a pretty minor variant on asking for the decomposition. May 28, 2018 at 16:57
• @Arnauld you're right about 12, and the fact that the ouptut code must give both score & decomposition. I'll make my next questions proof-read May 28, 2018 at 18:55

# JavaScript (ES6), 46 bytes

Returns an array where:

• the last term is the sum
• all preceding terms are the decomposition
f=(n,s=0)=>n-1?[k=1-++n%3,...f(n/3|0,s+k)]:[s]


Try it online!

• Unless I'm misreading the spec/test cases, it doesn't look like you need to include the total in the output. May 28, 2018 at 16:26
• @Shaggy I don't really know for sure. I've asked the OP. May 28, 2018 at 16:38

# Python 3, 53 bytes

Credit to Mr.Xcoder

f=lambda i,*s:i>1and f(-~i//3,*s,1--~i%3)or[s,sum(s)]


Try it online!

# Python 2, 55 bytes

f=lambda i,s=[]:i>1and f(-~i/3,s+[1--~i%3])or[s,sum(s)]


Try it online!

# Python 2, 58 bytes

i,s=input(),[]
while~-i:s+=1--~i%3,;i=-~i/3
print s,sum(s)


Try it online!

Returns list with decomposition and sum of it

• 53 bytes in Python 3 using recursion. The Python 2 equivalent recursive function should be about 55 bytes long. Keeping this as a Python 2 full program, while~-i saves a byte. May 28, 2018 at 16:42
• @Mr.Xcoder Thanks! Don't you want to post Python 3 solution as separate answer? May 28, 2018 at 16:51
• You're welcome! No, I'm good. Go ahead and use it however you want. May 28, 2018 at 16:52
• @Mr.Xcoder So there will be all solutions with credit to you :D May 28, 2018 at 16:56