An addition-subtraction chain, is a sequence \$a_1, a_2, a_3, ... ,a_n\$, such that \$a_1=1\$ and for all \$i > 1\$, there exist \$j,k<i\$ such that \$a_i = a_j \pm a_k\$.
Your task, is given a number \$x\$, find the shortest addition-subtraction chain, such that \$a_n = x\$.
Rules
- You can assume the input is a valid integer
- In case there are multiple optimal addition-subtraction chains, you can print any non-empty subset of them
- You may use any reasonable I/O method (you can output it reversed, with any separator you want, in any base you want, ect.)
Test cases
(these are one solution, you can output anything valid with the same length)
these are all the numbers with a addition subtraction chain of length 6 or less
-31 -> [1, 2, 4, 8, 16, -15, -31]
-30 -> [1, 2, 4, 8, 16, -15, -30]
-28 -> [1, 2, 4, 8, -6, -14, -28]
-24 -> [1, 2, 4, -2, -6, -12, -24]
-23 -> [1, 2, 4, 8, 12, 24, -23]
-22 -> [1, 2, 4, 6, -5, -11, -22]
-21 -> [1, 2, 3, 6, 12, -9, -21]
-20 -> [1, 2, 4, 6, -5, -10, -20]
-19 -> [1, 2, 4, 8, -3, -11, -19]
-18 -> [1, 2, 4, -1, 8, -9, -18]
-17 -> [1, 2, 4, -3, 7, -10, -17]
-16 -> [1, 2, 3, -1, -4, -8, -16]
-15 -> [1, 2, 4, 8, 16, -15]
-14 -> [1, 2, 4, 8, -7, -14]
-13 -> [1, 2, 4, 6, -3, -7, -13]
-12 -> [1, 2, 4, -3, -6, -12]
-11 -> [1, 2, 4, 6, -5, -11]
-10 -> [1, 2, 4, -2, -6, -10]
-9 -> [1, 2, 4, 8, -1, -9]
-8 -> [1, 2, 4, 8, 0, -8]
-7 -> [1, 2, 4, -3, -7]
-6 -> [1, 2, 4, 8, -6]
-5 -> [1, 2, 4, -3, -5]
-4 -> [1, 2, 4, 8, -4]
-3 -> [1, 2, -1, -3]
-2 -> [1, 2, 4, -2]
-1 -> [1, 0, -1]
0 -> [1, 0]
1 -> [1]
2 -> [1, 2]
3 -> [1, 2, 3]
4 -> [1, 2, 4]
5 -> [1, 2, 4, 5]
6 -> [1, 2, 4, 6]
7 -> [1, 2, 4, -3, 7]
8 -> [1, 2, 4, 8]
9 -> [1, 2, 3, 6, 9]
10 -> [1, 2, 4, 5, 10]
11 -> [1, 2, 4, 6, 5, 11]
12 -> [1, 2, 4, 6, 12]
13 -> [1, 2, 3, 5, 10, 13]
14 -> [1, 2, 4, 6, 10, 14]
15 -> [1, 2, 3, 6, 9, 15]
16 -> [1, 2, 4, 8, 16]
17 -> [1, 2, 4, 8, 9, 17]
18 -> [1, 2, 4, 8, 9, 18]
19 -> [1, 2, 4, 8, 9, 17, 19]
20 -> [1, 2, 4, 5, 10, 20]
21 -> [1, 2, 4, 8, 16, 5, 21]
22 -> [1, 2, 4, 8, 12, 24, 22]
23 -> [1, 2, 4, 8, 16, -15, 23]
24 -> [1, 2, 3, 6, 12, 24]
25 -> [1, 2, 4, 8, 12, 13, 25]
26 -> [1, 2, 4, 6, 10, 16, 26]
27 -> [1, 2, 4, 5, 9, 18, 27]
28 -> [1, 2, 4, 8, 12, 14, 28]
30 -> [1, 2, 4, 5, 10, 20, 30]
31 -> [1, 2, 4, 8, 16, -15, 31]
32 -> [1, 2, 4, 8, 16, 32]
33 -> [1, 2, 4, 8, 16, 32, 33]
34 -> [1, 2, 4, 8, 16, 17, 34]
36 -> [1, 2, 3, 6, 9, 18, 36]
40 -> [1, 2, 4, 8, 12, 20, 40]
48 -> [1, 2, 4, 8, 12, 24, 48]
64 -> [1, 2, 4, 8, 16, 32, 64]
you can find a list of all optimal addition subtraction chains for each of them here
This is code golf, so the shortest answer in bytes in each language wins.
-15
to make23
, or could you just use16-1
and then make23
using15+8
? \$\endgroup\$16-1
and then make23
. These are just a single solution my program found, other solutions with the same length exist for most of those. \$\endgroup\$