title: Find the shortest bracket numbers

text:
# Question
Title: Find the shortest bracket numbers
*Bracket numbers* provide a simple way to express large integers using only left bracket, space, and right bracket (`[ ]`).

A bracket number is defined as a string of one or more pairs of matching brackets `[...]` called *chunks*, each separated from its neighbors by zero or more spaces.

The number of spaces between each chunk defines the hyperoperation between them. No spaces means addition, 1 space means multiplication, 2 spaces means exponentiation, 3 spaces means tetration, and so on. Higher order hyperoperations take precedence, so tetration occurs before exponentiation, exponentiation occurs before multiplication, etc. They are also right-associative, so `a^b^c` is computed as `a^(b^c)`. (But `a^b*c` is still `(a^b)*c`.)

Each chunk may either be empty (`[]`) or contain another bracket number. Empty chunks have the value 0. Non-empty chunks have the value of their contained bracket number plus 1.

**Examples:** (`^^` is tetration, `^^^` is pentation)

* `[[]]` has value 1 because it is 0 (`[]`) incremented by 1
* `[[[]]]` has value 2 but so does `[[]][[]]` since the two ones (`[[]]`) are added
* `[[[]]] [[[[]]] [[[[]]]]][[[]]]` has value 20 = (2\*((2^3)+1))+2
* `[[[]]] [[[[]]]]` has value 65536 = 2^^^3 = 2^^(2^^2) = 2^^4 == 2^(2^(2^2))
* `[[[[]]]] [[[]]] [[]]` has value 7625597484987 = 3^^^(2^^^1) = 3^^^2 = 3^^3 = 3^(3^3)

In valid bracket numbers:

* There will never be leading or trailing spaces.
* There will always be at least one pair of matching brackets.
* All left brackets will have a matching right bracket.
* A space will never appear directly to the right of `[` nor to the left of `]`.
* The value is always a non-negative integer.

# Challenge

Notice that there may be many forms for a bracket number that give the same value. `[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]` and `[[[]]] [[[[]]]]` both represent 16, but the latter is much shorter.

Your challenge is to write an algorithm that attempts to find the shortest bracket number representation of a given value. For example, I believe the shortest way to represent 16 is with 17 characters as `[[[]]] [[[[]]]]`.

# Scoring (Updated)

Let *S* be the set of integers from 1 to 256 (inclusive) as well as the following ten values:

```
8191 13071 524287 2147483647 1449565302 1746268229 126528612 778085967 1553783038 997599288

```

(The first 4 are Mersenne primes, the rest are random.)

The submission that generates the shortest set of bracket numbers for everything in *S* will win. Your score is the sum of the lengths of your bracket numbers for all values in *S* (smaller is better).

With your code please submit a list of your bracket numbers for all of *S*, the exact order is not terribly important. e.g.:

```
1=[[]]
2=[[[]]]
3=[[[[]]]]
...
2147483647=[...]
...

```

(I know this is not the optimal scoring method but I am not set up to run a bunch of random heuristic tests on each submission. Sorry :( )

# Rules

* You may **not** hardcode any bracket numbers besides the trivial incremental solutions (`[], [[]], [[[]]], ...`). Your program must actually be looking for optimally short representations. (Though the results may be suboptimal.)
* Your algorithm should work for all non-negative integers below 2,147,483,648 (2^31). **You may not specifically focus on the values in *S*.**
* For any particular input, your algorithm should run in at most 10 minutes on a decent modern computer (~2.5Ghz processor, ~6GB RAM).
* In the (seemingly) rare chance of a tie the highest voted submission wins.
* If you copy another solution or revise it without attribution you will be disqualified.

# Answer
> 5 votes
# Python 11455b

This solution takes a greedy approach to finding ways to break down prime numbers, rather than an exhaustive approach. I need 9875b for 1-256 compared to 8181 for Martin's probably-optimal solution in that space.

A larger table of multiplication and exponentiation results yields slight improvements in the larger test cases. The solution below took about 7 minutes. Increasing runtime beyond 30 minutes has minimal impact on the output.

I, like Martin, had a problem with precedence. My solution in restricting operation selection may not be optimal.

```
#!/usr/bin/env python

# http://codegolf.stackexchange.com/questions/35480/find-the-shortest-bracket-numbers

import sys, math

reps = {}
forwards = {}
backwards = {}

MAX = 2**31

TABLE_SIZE = 2**12

def op_dec(op):
    if op>1:
        return op-1
    return op

def rep_op(a,op,b):
    return rep_num(a) +  (" "*op) + rep_num(b)
def min_rep_op(a,op,b,op_max):
    return min_rep(a,op_max) +  (" "*op) + min_rep(b,op_dec(op_max))

def rep_num(a):
    return ("["*(a+1)) + ("]"*(a+1))

def min_rep(n,op_max):
    if n < 9:
        return ("["*(n+1))+("]"*(n+1))
    for op in range(op_max,-1,-1):
        if (n, op) in reps:
            return reps[(n, op)]
    for op in range(op_max,-1,-1):
        if (n, op) in backwards:
            a,op,b = backwards[(n, op)]
            return min_rep_op(a,op,b,op_max)
    else:
        for m in rep_list:
            c = m[0]
            if c < n:
                r = n - c
                for op in range(op_max,-1,-1):
                    if (c, op) in backwards:
                        a,op,b = backwards[(c, op)]
                        if r<10:
                            return ("["*r) + min_rep_op(a,op,b,op_max) + ("]"*r)
                        else:
                            return "[" + min_rep(r-1,op_max) + min_rep_op(a,op,b,op_max) + "]"
                break

def expand(a,op,b):
    if op == 0:
        n = a+b
    elif op == 1:
        n = a*b
    elif op == 2:
        if b*math.log10(a) > math.log10(MAX):
            n = MAX
        else:
            n = a**b
    elif (a,op,b) in forwards:
        n = forwards[(a,op,b)]
    else: # tetration and higher
        t = a
        for i in xrange(b-1):
            t = expand(a,op-1,t)
            if t>=MAX:
                break
        n = t

    if n > MAX-1:
        n = MAX
    forwards[(a,op,b)] = n

    if (n, op) in backwards:
        c = len(rep_op(*backwards[(n, op)]))
        if c > (a*2+op+b*2):
            backwards[(n, op)] = (a,op,b)
    else:
        backwards[(n, op)] = (a,op,b)

    return n

t = 0

# populate the multiplication, exponentiation, and tetration tables
for op in range(1,4):
    for a in range((1,2,2,2)[op],TABLE_SIZE):
        for b in range((1,2,2,2)[op],TABLE_SIZE):
            t = expand(a,op,b)
            if t == MAX:
                break
rep_list = sorted(backwards.keys(),key=lambda x: x[0]*4-x[1],reverse=True)

for i in list(range(1, 257))+[8191,13071,524287,2147483647,1449565302,1746268229,126528612,778085967,1553783038,997599288]:
    t = min_rep(i,3)
    reps[i] = t
    print i, t

```

Output:

```
1 [[]]
2 [[[]]]
3 [[[[]]]]
4 [[[[[]]]]]
5 [[[[[[]]]]]]
6 [[[[[[[]]]]]]]
7 [[[[[[[[]]]]]]]]
8 [[[[[[[[[]]]]]]]]]
9 [[[[]]]]  [[[]]]
10 [[[[[[]]]]]] [[[]]]
11 [[[[[[[]]]]]] [[[]]]]
12 [[[[[[[]]]]]]] [[[]]]
13 [[[[[[[[]]]]]]] [[[]]]]
14 [[[[[[[[]]]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]]
106 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]
107 [[[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]]
108 [[[[[[[]]]]]]] [[[]]] [[[[]]]]  [[[]]]
109 [[[[[[[[]]]]]]] [[[]]] [[[[]]]]  [[[]]]]
110 [[[[[[[]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
111 [[[[[[[[]]]]]]]  [[[]]]] [[[[]]]]
112 [[[]]]   [[[[]]]] [[[[[[[[]]]]]]]]
113 [[[[]]]   [[[[]]]] [[[[[[[[]]]]]]]]]
114 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]]
115 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[]]]]]]
116 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[]]]]]
117 [[[[[[[[]]]]]]] [[[]]]] [[[[]]]]  [[[]]]
118 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[]]]
119 [[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]]]
120 [[[[[[]]]]]] [[[[]]]] [[[[[[[[[]]]]]]]]]
121 [[[[[[[]]]]]] [[[]]]]  [[[]]]
122 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[]]]
123 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[]]]]
124 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[]]]]]
125 [[[[[[]]]]]]  [[[[]]]]
126 [[[[[[[[]]]]]]]] [[[]]] [[[[]]]]  [[[]]]
127 [[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]  [[[]]]]
128 [[[]]]  [[[[[[[[]]]]]]]]
129 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[]]]]
130 [[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
131 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]]
132 [[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
133 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[]]]]]]]]
134 [[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[]]]
135 [[[[[[]]]]]] [[[[]]]] [[[[]]]]  [[[]]]
136 [[[[]]]   [[[[]]]]] [[[[[[[[[]]]]]]]]]
137 [[[[[]]]   [[[[]]]]] [[[[[[[[[]]]]]]]]]]
138 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]
139 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]]
140 [[[[[[[[]]]]]]]] [[[]]] [[[[[[]]]]]] [[[]]]
141 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[]]]]
142 [[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]] [[[]]]
143 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]] [[[]]]]
144 [[[[[[[]]]]]]] [[[]]]  [[[]]]
145 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[]]]]]]
146 [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[]]]
147 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]]]
148 [[[[[[[[]]]]]]]  [[[]]]] [[[[[]]]]]
149 [[[[[[[[[]]]]]]]  [[[]]]] [[[[[]]]]]]
150 [[[[[[]]]]]] [[[[]]]] [[[[[[]]]]]] [[[]]]
151 [[[[[[[]]]]]] [[[[]]]] [[[[[[]]]]]] [[[]]]]
152 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[[]]]]]]]]]
153 [[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]
154 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
155 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[]]]]]]
156 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]] [[[]]]
157 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]] [[[]]]]
158 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[]]]
159 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[]]]]
160 [[[]]]   [[[[]]]] [[[[[[]]]]]] [[[]]]
161 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[]]]]]]]]
162 [[[[[[[]]]]]]] [[[[]]]] [[[[]]]]  [[[]]]
163 [[[[[[[[]]]]]]] [[[[]]]] [[[[]]]]  [[[]]]]
164 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[]]]]]
165 [[[[[[]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
166 [[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]
167 [[[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]]
168 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[]]]]]]] [[[]]]
169 [[[[[[[[]]]]]]] [[[]]]]  [[[]]]
170 [[[[]]]   [[[[]]]]] [[[[[[]]]]]] [[[]]]
171 [[[[[[[[]]]]]]] [[[[]]]]] [[[[]]]]  [[[]]]
172 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[]]]]]
173 [[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[]]]]]]
174 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[]]]]]]]
175 [[[[[[]]]]]]  [[[]]] [[[[[[[[]]]]]]]]
176 [[[]]]   [[[[]]]] [[[[[[[]]]]]] [[[]]]]
177 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[[]]]]
178 [[[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]] [[[]]]
179 [[[[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]] [[[]]]]
180 [[[[[[]]]]]] [[[[[]]]]] [[[[]]]]  [[[]]]
181 [[[[[[[]]]]]] [[[[[]]]]] [[[[]]]]  [[[]]]]
182 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[[]]]]]]] [[[]]]]
183 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[[]]]]
184 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]]]]]
185 [[[[[[[[]]]]]]]  [[[]]]] [[[[[[]]]]]]
186 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[]]]]]]]
187 [[[[]]]   [[[[]]]]] [[[[[[[]]]]]] [[[]]]]
188 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[[]]]]]
189 [[[[[[[[]]]]]]]] [[[[]]]] [[[[]]]]  [[[]]]
190 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[]]]]]] [[[]]]
191 [[[[[[[[[]]]]]]] [[[[]]]]] [[[[[[]]]]]] [[[]]]]
192 [[[]]]   [[[[]]]] [[[[[[[]]]]]]] [[[]]]
193 [[[[]]]   [[[[]]]] [[[[[[[]]]]]]] [[[]]]]
194 [[[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]] [[[]]]
195 [[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
196 [[[[[[[[]]]]]]]] [[[]]]  [[[]]]
197 [[[[[[[[[]]]]]]]] [[[]]]  [[[]]]]
198 [[[[[[[]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
199 [[[[[[[[]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]]
200 [[[[[[]]]]]] [[[[[]]]]] [[[[[[]]]]]] [[[]]]
201 [[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]]]
202 [[[[[[[]]]]]] [[[]]]  [[[]]]] [[[]]]
203 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[]]]]]]]]
204 [[[[]]]   [[[[]]]]] [[[[[[[]]]]]]] [[[]]]
205 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[[]]]]]]
206 [[[[[]]]   [[[[]]]]] [[[[[[[]]]]]]]] [[[]]]
207 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[]]]]  [[[]]]
208 [[[]]]   [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
209 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]] [[[]]]]
210 [[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]
211 [[[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]]
212 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[[]]]]]
213 [[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]] [[[[]]]]
214 [[[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]] [[[]]]
215 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216 [[[[[[[]]]]]]]  [[[[]]]]
217 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
218 [[[[[[[[]]]]]]] [[[]]] [[[[]]]]  [[[]]]] [[[]]]
219 [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[[]]]]
220 [[[[[[[]]]]]] [[[]]]] [[[]]] [[[[[[]]]]]] [[[]]]
221 [[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]] [[[]]]]
222 [[[[[[[[]]]]]]]  [[[]]]] [[[[[[[]]]]]]]
223 [[[[[[[[[]]]]]]]  [[[]]]] [[[[[[[]]]]]]]]
224 [[[]]]   [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]
225 [[[[[[]]]]]] [[[[]]]]  [[[]]]
226 [[[[]]]   [[[[]]]] [[[[[[[[]]]]]]]]] [[[]]]
227 [[[[[]]]   [[[[]]]] [[[[[[[[]]]]]]]]] [[[]]]]
228 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]] [[[]]]
229 [[[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]] [[[]]]]
230 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
231 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
232 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[[]]]]]]]]]
233 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[[]]]]]]]]]]
234 [[[[[[[]]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
235 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[[[]]]]]]
236 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[[[]]]]]
237 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]]]
238 [[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]]] [[[]]]
239 [[[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]]] [[[]]]]
240 [[[[[[]]]]]] [[[[[]]]]] [[[[[[[]]]]]]] [[[]]]
241 [[[[[[[]]]]]] [[[[[]]]]] [[[[[[[]]]]]]] [[[]]]]
242 [[[[[[[]]]]]] [[[]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
243 [[[[]]]]  [[[[[[]]]]]]
244 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
245 [[[[[[[[]]]]]]]] [[[[[[]]]]]] [[[[[[[[]]]]]]]]
246 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[[[]]]]]]]
247 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[]]]]]]] [[[]]]]
248 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[[[]]]]]]]]]
249 [[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[[]]]]
250 [[[[[[]]]]]]  [[[]]] [[[[[[]]]]]] [[[]]]
251 [[[[[[[]]]]]]  [[[]]] [[[[[[]]]]]] [[[]]]]
252 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[]]]]]]] [[[]]]
253 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]] [[[]]]]
254 [[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]  [[[]]]] [[[]]]
255 [[[[]]]   [[[[]]]]] [[[[[[]]]]]] [[[[]]]]
256 [[[[[]]]]]   [[[]]]
8191 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[[]]]]]]]] [[[[[[]]]]]] [[[]]] [[[[]]]] [[[[]]]]]
13071 [[[[[[[[[[[]]]]]]] [[[[]]]] [[[[]]]]  [[[]]]] [[[[[]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]]
524287 [[[[[[[[[]]]]]]] [[[[]]]]] [[[]]] [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[[]]]] [[[[]]]]]
2147483647 [[[[[[[[[[[]]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]] [[[[]]]] [[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]][[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[]]]]]]] [[[[[[]]]]]]  [[[[]]]]]
1449565302 [[[[[[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]  [[[]]]] [[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]] [[[]]][[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[[[[[[[]]]]]]]] [[[[[]]]]]]  [[[[]]]]]
1746268229 [[[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]]  [[[[[]]]]]] [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[[]]]]]]] [[[[]]]]]][[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[[]]]]]]]] [[[[[]]]]]  [[[[]]]]]
126528612 [[[[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[]]]]]]] [[[]]]] [[[[[[[[]]]]]]]][[[[[[[]]]]]]  [[[]]] [[[[[[]]]]]] [[[]]]] [[[]]]  [[[[]]]]]
778085967 [[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]] [[[[[[[[]]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[[[]]]]]][[[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]]  [[[[[]]]]]]
1553783038 [[[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[[[[]]]]]]  [[[]]] [[[[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]] [[[[[[]]]]]] [[[]]]][[[[]]]   [[[[]]]] [[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]  [[[[]]]]]
997599288 [[[[[[[[]]]]]] [[[]]]] [[[[[[[[]]]]]]]] [[[[[[[]]]]]] [[[]]]] [[[]]]  [[[[[[]]]]]] [[[[[[[]]]]]] [[[]]]] [[[]]][[[[[[[[]]]]]]]  [[[]]]] [[[[]]]]  [[[[]]]]  [[[[]]]]]

```

# Answer
> 7 votes
## Mathematica

**Note:** This algorithm is never going to be able to get anywhere near the larger test numbers. I'd need a substantially different approach, so I'll just leave it as is for others to check their lower numbers against. You may consider this submission invalid.

Here is a start for the first 256 numbers (the others were added after I started, and I probably need to find a separate solution for those)

```
1=[[]]
2=[[[]]]
3=[[[[]]]]
4=[[[[[]]]]]
5=[[[[[[]]]]]]
6=[[[[[[[]]]]]]]
7=[[[[[[[[]]]]]]]]
8=[[[]]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[[[[]]]]]]]
84=[[[[[[[]]]]  [[[[[]]]]]]]]
85=[[[[[[[[]]]]  [[[[[]]]]]]]]]
86=[[[[[[[[[]]]]  [[[[[]]]]]]]]]]
87=[[[[[[]]]]   [[[]]]]] [[[[]]]]
88=[[[[[[[]]]]   [[[]]]]] [[[[]]]]]
89=[[[[[[[[]]]]   [[[]]]]] [[[[]]]]]]
90=[[[[[[[]]]]   [[[]]]]]] [[[[]]]]
91=[[[[[[[[]]]]   [[[]]]]]] [[[[]]]]]
92=[[[[[[[[[]]]]   [[[]]]]]] [[[[]]]]]]
93=[[[[[[[[]]]]   [[[]]]]]]] [[[[]]]]
94=[[[[[[[[[]]]]   [[[]]]]]]] [[[[]]]]]
95=[[[[[[]]]   [[[[]]]]]]] [[[[[[]]]]]]
96=[[[]]]  [[[[[[]]]]]] [[[[]]]]
97=[[[[]]]  [[[[[[]]]]]] [[[[]]]]]
98=[[[[[[[[]]]]]]]]  [[[]]] [[[]]]
99=[[[[]]]  [[[[[[]]]]]]] [[[[]]]]
100=[[[[[]]]]  [[[]]]]  [[[]]]
101=[[[[[[]]]]  [[[]]]]  [[[]]]]
102=[[[[[[[]]]]  [[[]]]]  [[[]]]]]
103=[[[[[[[[]]]]  [[[]]]]  [[[]]]]]]
104=[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]
105=[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]
106=[[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]]
107=[[[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]]]
108=[[[[]]]]   [[[]]] [[[[[]]]]]
109=[[[[[]]]]   [[[]]] [[[[[]]]]]]
110=[[[[[[]]]]   [[[]]] [[[[[]]]]]]]
111=[[[[[[[[]]]]]]]  [[[]]]] [[[[]]]]
112=[[[[[]]]]   [[[]]]] [[[[[]]]]]
113=[[[[[[]]]]   [[[]]]] [[[[[]]]]]]
114=[[[[[[[]]]]   [[[]]]] [[[[[]]]]]]]
115=[[[[[[[[]]]]   [[[]]]] [[[[[]]]]]]]]
116=[[[[[[]]]]   [[[]]]]] [[[[[]]]]]
117=[[[[[[[]]]]   [[[]]]]] [[[[[]]]]]]
118=[[[[[[[[]]]]   [[[]]]]] [[[[[]]]]]]]
119=[[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]]]
120=[[[[[[[]]]]   [[[]]]]]] [[[[[]]]]]
121=[[[[[[]]]]  [[[]]]]]  [[[]]]
122=[[[[[[[]]]]  [[[]]]]]  [[[]]]]
123=[[[[[[[[]]]]  [[[]]]]]  [[[]]]]]
124=[[[[[[[[[]]]]  [[[]]]]]  [[[]]]]]]
125=[[[[[[]]]]]]  [[[[]]]]
126=[[[[[[[]]]]]]  [[[[]]]]]
127=[[[[[[[[]]]]]]  [[[[]]]]]]
128=[[[]]]  [[[[[[[[]]]]]]]]
129=[[[[]]]  [[[[[[[[]]]]]]]]]
130=[[[[[]]]  [[[[[[[[]]]]]]]]]]
131=[[[[[[]]]  [[[[[[[[]]]]]]]]]]]
132=[[[[[[[]]]]]  [[[[]]]]]] [[[]]]
133=[[[[[[[[]]]]]  [[[[]]]]]] [[[]]]]
134=[[[[[[[[]]]]]  [[[[]]]]]]] [[[]]]
135=[[[[]]]]   [[[]]] [[[[[[]]]]]]
136=[[[[[]]]]   [[[]]] [[[[[[]]]]]]]
137=[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]
138=[[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]]
139=[[[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]]]
140=[[[[[]]]]   [[[]]]] [[[[[[]]]]]]
141=[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]
142=[[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]]
143=[[[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]]]
144=[[[[[[[]]]]]]]  [[[]]] [[[[[]]]]]
145=[[[[[[]]]]   [[[]]]]] [[[[[[]]]]]]
146=[[[[[[[]]]]   [[[]]]]] [[[[[[]]]]]]]
147=[[[[[[[[]]]]]]]]  [[[]]] [[[[]]]]
148=[[[[[[[[[]]]]]]]]  [[[]]] [[[[]]]]]
149=[[[[[[[[[[]]]]]]]]  [[[]]] [[[[]]]]]]
150=[[[[[[]]]]]]  [[[]]] [[[[[[[]]]]]]]
151=[[[[[[[]]]]]]  [[[]]] [[[[[[[]]]]]]]]
152=[[[[[[[[[]]]]]]]  [[[]]]]] [[[[[]]]]]
153=[[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]
154=[[[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]]
155=[[[[[[[[]]]]   [[[]]]]]]] [[[[[[]]]]]]
156=[[[[[[[]]]]]]  [[[]]]] [[[[[[[]]]]]]]
157=[[[[[[[[]]]]]]  [[[]]]] [[[[[[[]]]]]]]]
158=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]] [[[]]]
159=[[[[[[[[]]]]]]  [[[]]]] [[[]]]] [[[[]]]]
160=[[[]]]  [[[[[[]]]]]] [[[[[[]]]]]]
161=[[[[]]]  [[[[[[]]]]]] [[[[[[]]]]]]]
162=[[[[]]]]  [[[[[]]]]] [[[]]]
163=[[[[[]]]]  [[[[[]]]]] [[[]]]]
164=[[[[[]]]]  [[[[[]]]]]] [[[]]]
165=[[[[[[]]]]  [[[[[]]]]]] [[[]]]]
166=[[[[[[]]]]  [[[[[]]]]]]] [[[]]]
167=[[[[[[[]]]]  [[[[[]]]]]]] [[[]]]]
168=[[[[[[[]]]]  [[[[[]]]]]]]] [[[]]]
169=[[[[[[]]]]] [[[[]]]]]  [[[]]]
170=[[[[[[[]]]]] [[[[]]]]]  [[[]]]]
171=[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]
172=[[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]]
173=[[[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]]]
174=[[[[[[]]]]   [[[]]]]] [[[[[[[]]]]]]]
175=[[[[[[]]]]]]  [[[]]] [[[[[[[[]]]]]]]]
176=[[[]]]   [[[[]]]] [[[[[[]]]]  [[[]]]]]
177=[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]
178=[[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]]
179=[[[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]]]
180=[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]
181=[[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]]
182=[[[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]]]
183=[[[[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]]]]
184=[[[[[]]]]  [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
185=[[[[[[[[]]]]]]]  [[[]]]] [[[[[[]]]]]]
186=[[[[[[[[[]]]]]]]  [[[]]]] [[[[[[]]]]]]]
187=[[[[]]]   [[[[]]]]] [[[[[[]]]]  [[[]]]]]
188=[[[[[]]]   [[[[]]]]] [[[[[[]]]]  [[[]]]]]]
189=[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]
190=[[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]]
191=[[[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]]]
192=[[[[[]]]]]  [[[[]]]] [[[[]]]]
193=[[[[[[]]]]]  [[[[]]]] [[[[]]]]]
194=[[[[[[[]]]]]  [[[[]]]] [[[[]]]]]]
195=[[[[[[]]]]]  [[[[]]]]] [[[[]]]]
196=[[[[[[[]]]]] [[[[]]]]]]  [[[]]]
197=[[[[[[[[]]]]] [[[[]]]]]]  [[[]]]]
198=[[[[[[[]]]]]  [[[[]]]]]] [[[[]]]]
199=[[[[[[[[]]]]]  [[[[]]]]]] [[[[]]]]]
200=[[[[[]]]]  [[[]]]]  [[[]]] [[[]]]
201=[[[[[[]]]]  [[[]]]]  [[[]]] [[[]]]]
202=[[[[[[]]]]  [[[]]]]  [[[]]]] [[[]]]
203=[[[[[[[]]]]  [[[]]]]  [[[]]]] [[[]]]]
204=[[[[[[[[[]]]]]  [[[[]]]]]]]] [[[[]]]]
205=[[[[[[[[[[]]]]]  [[[[]]]]]]]] [[[[]]]]]
206=[[[[[[[[]]]]  [[[]]]]  [[[]]]]]] [[[]]]
207=[[[[[[[[[[]]]]]  [[[[]]]]]]]]] [[[[]]]]
208=[[[]]]   [[[[]]]] [[[[[[]]]]] [[[[]]]]]
209=[[[[]]]   [[[[]]]] [[[[[[]]]]] [[[[]]]]]]
210=[[[[[[[]]]]   [[[]]]]]] [[[[[[[[]]]]]]]]
211=[[[[[[[[]]]]   [[[]]]]]] [[[[[[[[]]]]]]]]]
212=[[[[[[[[]]]]]]  [[[]]]] [[[]]]] [[[[[]]]]]
213=[[[[[[[[[[[[]]]]]  [[[[]]]]]]]]]]] [[[[]]]]
214=[[[[[[[[[[[[[]]]]]  [[[[]]]]]]]]]]] [[[[]]]]]
215=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216=[[[[[[[]]]]]]]  [[[[]]]]
217=[[[[[[[[]]]]]]]  [[[[]]]]]
218=[[[[[[[[[]]]]]]]  [[[[]]]]]]
219=[[[[[[[[[[]]]]]]]  [[[[]]]]]]]
220=[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]
221=[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]
222=[[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]]
223=[[[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]]]
224=[[[[[]]]]   [[[]]]] [[[]]]  [[[[]]]]
225=[[[[[[]]]]]]  [[[]]] [[[[]]]]  [[[]]]
226=[[[[[[[]]]]]]  [[[]]] [[[[]]]]  [[[]]]]
227=[[[[[[[[]]]]]]  [[[]]] [[[[]]]]  [[[]]]]]
228=[[[[[[]]]]   [[[]]]] [[[]]]] [[[[[]]]]]
229=[[[[[[[]]]]   [[[]]]] [[[]]]] [[[[[]]]]]]
230=[[[[[[[[]]]]   [[[]]]] [[[]]]] [[[[[]]]]]]]
231=[[[[]]]  [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
232=[[[[[[]]]]   [[[]]]]] [[[]]]  [[[[]]]]
233=[[[[[[[]]]]   [[[]]]]] [[[]]]  [[[[]]]]]
234=[[[[[[[]]]]]]  [[[]]]] [[[[]]]]  [[[]]]
235=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]  [[[]]]]
236=[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[[]]]]]
237=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]] [[[[]]]]
238=[[[[[]]]  [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]
239=[[[[[[]]]  [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]]
240=[[[]]]   [[[[]]]] [[[[[[]]]]]] [[[[]]]]
241=[[[[]]]   [[[[]]]] [[[[[[]]]]]] [[[[]]]]]
242=[[[[[[]]]]  [[[]]]]]  [[[]]] [[[]]]
243=[[[[]]]]  [[[[[[]]]]]]
244=[[[[[]]]]  [[[[[[]]]]]]]
245=[[[[[[]]]]  [[[[[[]]]]]]]]
246=[[[[[[[]]]]  [[[[[[]]]]]]]]]
247=[[[[[[[[]]]]  [[[[[[]]]]]]]]]]
248=[[[[[[[[[]]]]  [[[[[[]]]]]]]]]]]
249=[[[[[[]]]]  [[[[[]]]]]]] [[[[]]]]
250=[[[[[[]]]]]]  [[[[]]]] [[[]]]
251=[[[[[[[]]]]]]  [[[[]]]] [[[]]]]
252=[[[[[[[]]]]]]  [[[[]]]]] [[[]]]
253=[[[[[[[[]]]]]]  [[[[]]]]] [[[]]]]
254=[[[[[[[[]]]]]]  [[[[]]]]]] [[[]]]
255=[[[[[[[[[]]]]]]  [[[[]]]]]] [[[]]]]
256=[[[[[]]]]]   [[[]]]

```

The total length of the first 256 numbers is **7963** characters. I don't know if this is optimal.

Ignoring addition, the results for 8191 and 13071 were found in a few seconds and 524387 in a couple of minutes as

```
8191=[[[[[[[[]]]]]]  [[[[]]]]] [[[[[[]]]]]  [[[[]]]]]]
13071=[[[[[[[[]]]]]  [[[[]]]]]]  [[[]]]] [[[[]]]]
524387=[[[[[[[[]]]]]  [[[[]]]]] [[[[[]]]]]  [[[[]]]]] [[[[[[[]]]]]]  [[[[]]]]]]

```

at **164** characters together.

Here is the code:

```
ClearAll[repr, sl, i, j, op, re, frontop, rearop, lastop];
repr[n_] = "";
repr[0] = "[]";
(*Hard-code higher-order solutions*)
repr[65536] = "[[[]]]    [[[[]]]]";
repr[16] = "[[[]]]   [[[[]]]]";
repr[27] = "[[[[]]]]   [[[]]]";
repr[256] = "[[[[[]]]]]   [[[]]]";
repr[3125] = "[[[[[[]]]]]]   [[[]]]";
repr[46656] = "[[[[[[[]]]]]]]   [[[]]]";
repr[823543] = "[[[[[[[[]]]]]]]]   [[[]]]";
repr[16777216] = "[[[[[[[[[]]]]]]]]]   [[[]]]";
repr[387420489] = "[[[[[[[[[[]]]]]]]]]]   [[[]]]";
frontop[n_] = 2;
rearop[n_] = 2;
sl[n_] := If[repr[n] == "", Infinity, StringLength@repr@n];
n = 256;
op[0] := (# + #2) &
op[1] := (#*#2) &
op[2] := (#^#2) &
re[0] := (repr@# <> repr@#2) &
re[1] := (repr@# <> " " <> repr@#2) &
re[2] := (repr@# <> "  " <> repr@#2) &
For[i = 0, i < n, ++i,
  If[sl[i + 1] >= sl[i] + 2,
   repr[i + 1] = "[" <> repr[i] <> "]";
   frontop[i + 1] = 2; rearop[i + 1] = 2
   ];
  For[m = 0, m < 3, ++m,
   If[rearop[i] >= m,
    For[j = 1, j <= i, ++j,
     If[frontop[j] < m || (res = op[m][i, j]) > n, Break[]];
     rep = re[m][i, j];
     If[sl[res] > StringLength@rep ||
       sl[res] == StringLength@rep && m > frontop[res],
      repr[res] = rep;
      If[m == 2,
       frontop[res] = 2; rearop[res] = 1,
       frontop[res] = m;
       rearop[res] = m
       ]
      ]
     ]
    ];
   If[frontop[i] >= m,
    For[j = 1, j <= i, ++j,
     If[rearop[j] < m || (res = op[m][j, i]) > n, Break[]];
     rep = re[m][j, i];
     If[sl[res] > StringLength@rep ||
       sl[res] == StringLength@rep && m > frontop[res],
      repr[res] = rep;
      If[m == 2,
       frontop[res] = 2; rearop[res] = 1,
       frontop[res] = m;
       rearop[res] = m
       ]
      ]
     ]
    ]
   ];
  ];

```

I used an exhaustive search up to exponentiation. There is no tetration or higher-order operations. I just tried the higher-order operations manually, and there's only a handful combinations which actually yield numbers below 2<sup>31</sup>, so I just hardcoded those that work.

**Edit:** My previous solution didn't not bother about precedence, it just threw things together. ~~Now I *think* my new code fixes that,~~ but non of the first 256 numbers have changed, nor has 8191 (which was valid before, I checked)... and it's to late for me to tell right now if my code *actually* fixed it. I'll have another look tomorrow and also add an explanation, because now with the precedence checking it's a bit convoluted (hopefully it should reduce search time though).

**Edit:** Okay, there were some bugs as expected. I think I fixed it now, increasing the total length for 1 - 256 to **7963**. I'm not sure this is optimal any longer, because it might be possible to find shorter solutions from suboptimal parts if they allow higher-order operations. An explanation will follow when I manage to clean up the code a bit.

# Answer
> 1 votes
# Python 9219b

This is my second entry. I started from scratch and tried a new arrangement of the data, including using the blist package for sorted lists and dicts, and some new approaches for finding large solutions. I think I've got an optimal 1-256. Increasing runtime from 30s to 4m shortened the big test cases by about 30 bytes.

```
# https://pypi.python.org/pypi/blist/
# provides sorteddict
from blist import *

import math, sys

TABLE_SIZE=2**8
MAX_INT = 2**31

repr = sorteddict()

for i in range(12):
    repr[i] = sorteddict({(i*2+2,-1,-1):("["*(i+1)+"]"*(i+1), str(i))});

repr    [65536] = sorteddict({(18, 4, 4):("[[[]]]    [[[[]]]]", "2^^^3")}); # 2^^^3 = 2^^(2^^2) = 2^(2^(2^2))
repr       [16] = sorteddict({(17, 3, 3):("[[[]]]   [[[[]]]]", "2^^3")}); # 2^^3 = 2^(2^2)
repr       [27] = sorteddict({(17, 3, 3):("[[[[]]]]   [[[]]]", "3^^2")}); # 3^^2 = 3^3
repr      [256] = sorteddict({(19, 3, 3):("[[[[[]]]]]   [[[]]]", "4^^2")}); # 4^^2 = 4^4
repr     [3125] = sorteddict({(21, 3, 3):("[[[[[[]]]]]]   [[[]]]", "5^^2")}); # 5^^2 = 5^5
repr    [46656] = sorteddict({(23, 3, 3):("[[[[[[[]]]]]]]   [[[]]]", "6^^2")}); # 6^^2 = 6^6
repr   [823543] = sorteddict({(25, 3, 3):("[[[[[[[[]]]]]]]]   [[[]]]", "7^^2")}); # 7^^2 = 7^7
repr [16777216] = sorteddict({(27, 3, 3):("[[[[[[[[[]]]]]]]]]   [[[]]]", "8^^2")}); # 8^^2 = 8^8
repr[387420489] = sorteddict({(29, 3, 3):("[[[[[[[[[[]]]]]]]]]]   [[[]]]", "9^^2")}); # 9^^2 = 9^9

def expr_to_repr(a,op,b):
    rep_a = None
    for d,r in repr[a].iteritems():
        op_min, op_max = ((0,9),(1,9),(3,9))[op]
        if (d[1]==-1 or d[1]>=op_min) and d[2]<=op_max:
            rep_a = (d,r)
            break
    if not rep_a:
        rep_a = ((a*2+2,-1,-1),("["*(a+1)+"]"*(a+1), str(a)));

    rep_b = None
    for d,r in repr[b].iteritems():
        op_min, op_max = ((0,9),(1,9),(3,9))[op]
        if (d[1]==-1 or d[1]>=op_min) and d[2]<=op_max:
            rep_b = (d,r)
            break
    if not rep_b:
        rep_b = ((b*2+2,-1,-1),("["*(b+1)+"]"*(b+1), str(b)));

    r = rep_a[1][0] + " "*op + rep_b[1][0]

    return (
            (
                len(r),
                min(op, rep_a[0][1] if rep_a[0][1]!=-1 else op, rep_b[0][1] if rep_b[0][1]!=-1 else op),
                max(op, rep_a[0][2], rep_b[0][2])
            ),
            (
                r,
                expr_to_string(rep_a[1][1],op,rep_b[1][1])
            )
        );

def opsym(op):
    return ("+","*","^","^^")[op]

def expr_to_string(a,op,b):
    return str(a) + opsym(op) + str(b)

def calc(a,op,b):
    if op == 0:
        return min(a+b,MAX_INT)
    elif op == 1:
        return min(a*b,MAX_INT)
    elif op == 2:
        if (b*math.log10(a)>math.log10(MAX_INT)):
            return MAX_INT
        return min(a**b,MAX_INT)
    else:
        t = a
        for h in range(b):
            t = calc(a,op-1,t)
            if t>=MAX_INT:
                t = MAX_INT
                break
        return t

def populate_repr(a,op,b):
    o = (a,op,b)
    n = calc(*o)
    if n == MAX_INT:
        return n
    if n not in repr:
        repr[n] = sorteddict()
    r = expr_to_repr(*o)
    if conditional_replace_repr(n,r):
        for i in range(1,11):
            conditional_replace_repr(n+i,
                (
                    (
                        r[0][0]+i*2,
                        -1,
                        -1
                    ),
                    (
                        "["*i + r[1][0] + "]"*i,
                        "(" + r[1][1] + "+" + str(i) + ")"
                    )
                )
            )
    return n

def conditional_replace_repr(n,new_rep):
    if n not in repr:
        repr[n] = sorteddict()
        repr[n][new_rep[0]] = new_rep[1]
        return True
    found = None
    repl = False
    for d, r in repr[n].iteritems():
        if d[1] == new_rep[0][1] and d[2] == new_rep[0][2]:
            found = d
            if d[0] > new_rep[0][0]:
                repl = True
            break
    if (not found) or (found and repl):
        repr[n][new_rep[0]] = new_rep[1]
        if found:
            del repr[n][found]
        return True
    return False

def vaguely_decent_repr(n):
    if n <= TABLE_SIZE:
        return repr[n].iteritems().next()[1][0]
    if n in repr:
        return repr[n].iteritems().next()[1][0]
    else:
        keys = sorted(repr.keys(),reverse=True)
        best_rep = None
        tested = 0
        for i in keys:
            if i>n:
                continue
            if tested > 10:
                break
            tested += 1
            cand_rep = vaguely_decent_repr(n-i) + repr[i].iteritems().next()[1][0]
            if (not best_rep) or len(cand_rep) < len(best_rep):
                best_rep = cand_rep
        return best_rep

keys = repr.keys()
for k in keys:
    for d,r in repr[k].iteritems():
        for i in range(1,11):
            conditional_replace_repr(k+i,
                (
                    (
                        d[0]+i*2,
                        -1,
                        -1
                    ),
                    (
                        "["*i + r[0] + "]"*i,
                        "(" + r[1] + "+" + str(i) + ")"
                    )
                )
            )

# initialize the repr array with results of 1..256, 2+2 up to TABLE_SIZE^TABLE_SIZE
for row in range(2,TABLE_SIZE+1):
    for col in range(2,row):
        for op in range(1,3):
            populate_repr(row,op,col)
            if op > 1:
                populate_repr(col,op,row)
    for op in range(1,3):
        populate_repr(row,op,row)
    if row > 10:
        for frac in range(1,10):
            rep_a = repr[row-frac].iteritems().next()
            conditional_replace_repr(row,
                (
                    (
                        rep_a[0][0] + frac*2,
                        -1,
                        -1
                    ),
                    (
                        "["*frac + rep_a[1][0] + "]"*frac,
                        "(" + rep_a[1][1] + "+" + str(frac) + ")"
                    )
                )
            )
        for frac in range(10,row/2):
            rep_a = repr[frac].iteritems().next()
            rep_b = repr[row-frac].iteritems().next()
            conditional_replace_repr(row,
                (
                    (
                        rep_a[0][0]+rep_b[0][0],
                        min(rep_a[0][1],rep_b[0][1]),
                        max(rep_a[0][2],rep_b[0][2])
                    ),
                    (
                        rep_a[1][0] + rep_b[1][0],
                        rep_a[1][1] + "+" + rep_b[1][1]
                    )
                )
            )

# for n,reps in repr.iteritems():
#   for d,r in reps.iteritems():

for n in range(1,257):
    print str(n)+"="+repr[n].iteritems().next()[1][0]

for n in (8191,13071,524287,2147483647,1449565302,1746268229,126528612,778085967,1553783038,997599288):
    print str(n)+"="+vaguely_decent_repr(n)

```

Output:

```
1=[[]]
2=[[[]]]
3=[[[[]]]]
4=[[[[[]]]]]
5=[[[[[[]]]]]]
6=[[[[[[[]]]]]]]
7=[[[[[[[[]]]]]]]]
8=[[[]]]  [[[[]]]]
9=[[[[]]]]  [[[]]]
10=[[[[[]]]]  [[[]]]]
11=[[[[[[]]]]  [[[]]]]]
12=[[[[[]]]]] [[[[]]]]
13=[[[[[[]]]]] [[[[]]]]]
14=[[[[[[[]]]]] [[[[]]]]]]
15=[[[[[[]]]]]] [[[[]]]]
16=[[[]]]   [[[[]]]]
17=[[[[]]]   [[[[]]]]]
18=[[[[[]]]   [[[[]]]]]]
19=[[[[[[]]]   [[[[]]]]]]]
20=[[[[[[]]]]]] [[[[[]]]]]
21=[[[[[[[]]]]]] [[[[[]]]]]]
22=[[[[[[[[]]]]]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   [[[]]]]]]] [[[[]]]]
94=[[[[[[[[[]]]]   [[[]]]]]]] [[[[]]]]]
95=[[[[[[]]]   [[[[]]]]]]] [[[[[[]]]]]]
96=[[[]]]  [[[[[[]]]]]] [[[[]]]]
97=[[[[]]]  [[[[[[]]]]]] [[[[]]]]]
98=[[[[[[[[]]]]]]]]  [[[]]] [[[]]]
99=[[[[]]]  [[[[[[]]]]]]] [[[[]]]]
100=[[[[[]]]]  [[[]]]]  [[[]]]
101=[[[[[[]]]]  [[[]]]]  [[[]]]]
102=[[[[[[[]]]]  [[[]]]]  [[[]]]]]
103=[[[[[[[[]]]]  [[[]]]]  [[[]]]]]]
104=[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]
105=[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]
106=[[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]]
107=[[[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]]]
108=[[[[]]]]   [[[]]] [[[[[]]]]]
109=[[[[[]]]]   [[[]]] [[[[[]]]]]]
110=[[[[[[]]]]   [[[]]] [[[[[]]]]]]]
111=[[[[[[[[]]]]]]]  [[[]]]] [[[[]]]]
112=[[[[[]]]]   [[[]]]] [[[[[]]]]]
113=[[[[[[]]]]   [[[]]]] [[[[[]]]]]]
114=[[[[[[[]]]]   [[[]]]] [[[[[]]]]]]]
115=[[[[[[[[]]]]   [[[]]]] [[[[[]]]]]]]]
116=[[[[[[]]]]   [[[]]]]] [[[[[]]]]]
117=[[[[[[[]]]]   [[[]]]]] [[[[[]]]]]]
118=[[[[[[[[]]]]   [[[]]]]] [[[[[]]]]]]]
119=[[[[]]]   [[[[]]]]] [[[[[[[[]]]]]]]]
120=[[[[[[[]]]]   [[[]]]]]] [[[[[]]]]]
121=[[[[[[]]]]  [[[]]]]]  [[[]]]
122=[[[[[[[]]]]  [[[]]]]]  [[[]]]]
123=[[[[[[[[]]]]  [[[]]]]]  [[[]]]]]
124=[[[[[[[[[]]]]  [[[]]]]]  [[[]]]]]]
125=[[[[[[]]]]]]  [[[[]]]]
126=[[[[[[[]]]]]]  [[[[]]]]]
127=[[[[[[[[]]]]]]  [[[[]]]]]]
128=[[[]]]  [[[[[[[[]]]]]]]]
129=[[[[]]]  [[[[[[[[]]]]]]]]]
130=[[[[[]]]  [[[[[[[[]]]]]]]]]]
131=[[[[[[]]]  [[[[[[[[]]]]]]]]]]]
132=[[[[[[[]]]]]  [[[[]]]]]] [[[]]]
133=[[[[[[[[]]]]]  [[[[]]]]]] [[[]]]]
134=[[[[[[[[]]]]]  [[[[]]]]]]] [[[]]]
135=[[[[]]]]   [[[]]] [[[[[[]]]]]]
136=[[[[[]]]]   [[[]]] [[[[[[]]]]]]]
137=[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]
138=[[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]]
139=[[[[[[[[]]]]   [[[]]] [[[[[[]]]]]]]]]]
140=[[[[[]]]]   [[[]]]] [[[[[[]]]]]]
141=[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]
142=[[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]]
143=[[[[[[[[]]]]   [[[]]]] [[[[[[]]]]]]]]]
144=[[[[[[[]]]]  [[[]]]]]]  [[[]]]
145=[[[[[[[[]]]]  [[[]]]]]]  [[[]]]]
146=[[[[[[[[[]]]]  [[[]]]]]]  [[[]]]]]
147=[[[[[[[[]]]]]]]]  [[[]]] [[[[]]]]
148=[[[[[[[[[]]]]]]]]  [[[]]] [[[[]]]]]
149=[[[[[[[[[]]]]]]]  [[[]]]] [[[[[]]]]]]
150=[[[[[[[[[]]]]]]]]  [[[]]]] [[[[]]]]
151=[[[[[[[]]]]]]  [[[]]] [[[[[[[]]]]]]]]
152=[[[[[[[[[]]]]]]]  [[[]]]]] [[[[[]]]]]
153=[[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]
154=[[[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]]
155=[[[[[[[[]]]]   [[[]]]]]]] [[[[[[]]]]]]
156=[[[[[[[]]]]]]  [[[]]]] [[[[[[[]]]]]]]
157=[[[[[[[[]]]]]]  [[[]]]] [[[[[[[]]]]]]]]
158=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]] [[[]]]
159=[[[[[[[[]]]]]]  [[[]]]] [[[]]]] [[[[]]]]
160=[[[]]]  [[[[[[]]]]]] [[[[[[]]]]]]
161=[[[[]]]  [[[[[[]]]]]] [[[[[[]]]]]]]
162=[[[[]]]]  [[[[[]]]]] [[[]]]
163=[[[[[]]]]  [[[[[]]]]] [[[]]]]
164=[[[[[]]]]  [[[[[]]]]]] [[[]]]
165=[[[[[[]]]]  [[[[[]]]]]] [[[]]]]
166=[[[[[[]]]]  [[[[[]]]]]]] [[[]]]
167=[[[[[[[]]]]  [[[[[]]]]]]] [[[]]]]
168=[[[[[[[]]]]  [[[[[]]]]]]]] [[[]]]
169=[[[[[[]]]]] [[[[]]]]]  [[[]]]
170=[[[[[[[]]]]] [[[[]]]]]  [[[]]]]
171=[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]
172=[[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]]
173=[[[[[[[[[[]]]]] [[[[]]]]]  [[[]]]]]]]
174=[[[[[[]]]]   [[[]]]]] [[[[[[[]]]]]]]
175=[[[[[[]]]]]]  [[[]]] [[[[[[[[]]]]]]]]
176=[[[]]]   [[[[]]]] [[[[[[]]]]  [[[]]]]]
177=[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]
178=[[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]]
179=[[[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[]]]]]]
180=[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]
181=[[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]]
182=[[[[[[[[[]]]]]]]  [[[]]] [[[[[[]]]]]]]]
183=[[[[[[[[]]]]]]  [[[]]]] [[[[[[[[]]]]]]]]]
184=[[[[[]]]]  [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
185=[[[[[[[[]]]]]]]  [[[]]]] [[[[[[]]]]]]
186=[[[[[[[[[]]]]]]]  [[[]]]] [[[[[[]]]]]]]
187=[[[[]]]   [[[[]]]]] [[[[[[]]]]  [[[]]]]]
188=[[[[[]]]   [[[[]]]]] [[[[[[]]]]  [[[]]]]]]
189=[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]
190=[[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]]
191=[[[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]]]]
192=[[[[[]]]]]  [[[[]]]] [[[[]]]]
193=[[[[[[]]]]]  [[[[]]]] [[[[]]]]]
194=[[[[[[[]]]]]  [[[[]]]] [[[[]]]]]]
195=[[[[[[]]]]]  [[[[]]]]] [[[[]]]]
196=[[[[[[[]]]]] [[[[]]]]]]  [[[]]]
197=[[[[[[[[]]]]] [[[[]]]]]]  [[[]]]]
198=[[[[[[[]]]]]  [[[[]]]]]] [[[[]]]]
199=[[[[[[[[]]]]]  [[[[]]]]]] [[[[]]]]]
200=[[[[[]]]]  [[[]]]]  [[[]]] [[[]]]
201=[[[[[[]]]]  [[[]]]]  [[[]]] [[[]]]]
202=[[[[[[]]]]  [[[]]]]  [[[]]]] [[[]]]
203=[[[[[[[]]]]  [[[]]]]  [[[]]]] [[[]]]]
204=[[[[[[[[[]]]]]  [[[[]]]]]]]] [[[[]]]]
205=[[[[[[[[[[]]]]]  [[[[]]]]]]]] [[[[]]]]]
206=[[[[[[[[]]]]  [[[]]]]  [[[]]]]]] [[[]]]
207=[[[[[[[[[[]]]]]  [[[[]]]]]]]]] [[[[]]]]
208=[[[[[[[]]]]]]  [[[]]]] [[[]]]  [[[[]]]]
209=[[[[]]]   [[[[]]]] [[[[[[]]]]] [[[[]]]]]]
210=[[[[[[[]]]]   [[[]]]]]] [[[[[[[[]]]]]]]]
211=[[[[[[[[]]]]   [[[]]]]]] [[[[[[[[]]]]]]]]]
212=[[[[[[[[]]]]]]  [[[]]]] [[[]]]] [[[[[]]]]]
213=[[[[[[[[[[[[]]]]]  [[[[]]]]]]]]]]] [[[[]]]]
214=[[[[[[[[[[[[[]]]]]  [[[[]]]]]]]]]]] [[[[]]]]]
215=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216=[[[[[[[]]]]]]]  [[[[]]]]
217=[[[[[[[[]]]]]]]  [[[[]]]]]
218=[[[[[[[[[]]]]]]]  [[[[]]]]]]
219=[[[[[[[[[[]]]]]]]  [[[[]]]]]]]
220=[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]
221=[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]
222=[[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]]
223=[[[[[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]]]]
224=[[[[[]]]]   [[[]]]] [[[]]]  [[[[]]]]
225=[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]
226=[[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]]
227=[[[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]]]
228=[[[[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]]]]
229=[[[[[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]]]]]
230=[[[[[[[[[[[[[]]]]] [[[[]]]]]]]  [[[]]]]]]]]
231=[[[[]]]  [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
232=[[[[[[]]]]   [[[]]]]] [[[]]]  [[[[]]]]
233=[[[[[[[]]]]   [[[]]]]] [[[]]]  [[[[]]]]]
234=[[[[[[[]]]]]]  [[[]]]] [[[[]]]]  [[[]]]
235=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]  [[[]]]]
236=[[[[[[[]]]]   [[[]]]]] [[[]]]] [[[[[]]]]]
237=[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]] [[[[]]]]
238=[[[[[]]]  [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]
239=[[[[[[]]]  [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]]
240=[[[]]]   [[[[]]]] [[[[[[]]]]]] [[[[]]]]
241=[[[[]]]   [[[[]]]] [[[[[[]]]]]] [[[[]]]]]
242=[[[[[[]]]]  [[[]]]]]  [[[]]] [[[]]]
243=[[[[]]]]  [[[[[[]]]]]]
244=[[[[[]]]]  [[[[[[]]]]]]]
245=[[[[[[]]]]  [[[[[[]]]]]]]]
246=[[[[[[[]]]]  [[[[[[]]]]]]]]]
247=[[[[[[[[]]]]  [[[[[[]]]]]]]]]]
248=[[[[[[[[[]]]]  [[[[[[]]]]]]]]]]]
249=[[[[[[]]]]  [[[[[]]]]]]] [[[[]]]]
250=[[[[[[]]]]]]  [[[[]]]] [[[]]]
251=[[[[[[[]]]]]]  [[[[]]]] [[[]]]]
252=[[[[[[[]]]]]]  [[[[]]]]] [[[]]]
253=[[[[[[[[]]]]]]  [[[[]]]]] [[[]]]]
254=[[[[[[[[]]]]]]  [[[[]]]]]] [[[]]]
255=[[[[[[[[[]]]]]]  [[[[]]]]]] [[[]]]]
256=[[[[[]]]]]   [[[]]]
8191=[[[[[[[[]]]]]]  [[[[]]]]] [[[[[[]]]]]  [[[[]]]]]]
13071=[[[[[[[[[]]]]  [[[]]]]]  [[[]]] [[[[]]]]   [[[]]] [[[[[]]]]]]]]
524287=[[[[]]]]   [[[]]] [[[[[[[[]]]]]]]] [[[[[[]]]]]  [[[[]]]]][[[[[[[[[[[]]]]]]  [[[]]]] [[[[]]]]]]  [[[[]]]]]]
2147483647=[[[[[[]]]]]]  [[[[]]]] [[[[[]]]]] [[[[]]]][[[[]]]   [[[[]]]]]  [[[[[]]]]][[[[[[[[[[[]]]]]]]  [[[[]]]]]]]]  [[[[]]]][[[[[[[[[[[[[[[]]]]]  [[[[]]]]]]]]]]] [[[[]]]]]]  [[[[[]]]]]]
1449565302=[[[[[[[[[]]]]  [[[]]]]]]  [[[]]]]] [[[[[[[[]]]]  [[[[[]]]]]]]]][[[[[]]]   [[[[]]]]] [[[[]]]]  [[[]]]]  [[[[]]]][[[[[[[[[[[]]]]]  [[[[]]]] [[[[]]]]]]]  [[[[[]]]]]]]]
1746268229=[[[[[[[]]]]]]]  [[[[]]]] [[[[]]]  [[[[[[[[]]]]]]]]][[[[]]]]   [[[]]]  [[[[[[]]]]]][[[[[[[[[[]]]]  [[[]]]]  [[[]]]] [[[]]]]]  [[[[[]]]]]]]
126528612=[[[[[[]]]]  [[[[[[]]]]]]]] [[[[[]]]]][[[[[[[]]]]]]]  [[[[[[[[]]]]]]]][[[[[[[[[]]]]]]  [[[]]]] [[[[[]]]]]]]  [[[[[]]]]]
778085967=[[[[[[[[[]]]]  [[[[[]]]]]]]]]] [[[[[[]]]]]]  [[[]]][[[[[[[]]]]]  [[[[]]]]]]  [[[[]]]][[[[[[[]]]]  [[[[[]]]]]]] [[[]]]]  [[[[[]]]]]
1553783038=[[[[[]]]  [[[[[[[[]]]]]]]]]] [[[[[[[]]]]   [[[]]]]]][[[[[]]]   [[[[]]]]]]  [[[[[]]]]][[[[[[[[[]]]]  [[[]]]]  [[[]]]]]] [[[]]]]  [[[[]]]][[[[[[[[]]]  [[[[[[]]]]]]]]  [[[[[[[]]]]]]]]]]
997599288=[[[[[]]]]   [[[]]] [[[[[[]]]]]]] [[[[[[[[]]]]]  [[[[]]]]]]][[[[[[[[]]]]]] [[[[[]]]]]]]  [[[[[[]]]]]][[[[[[[[[[]]]]   [[[]]]]]]] [[[]]]]  [[[[[[]]]]]]]

```

7944b for 1-256

1275b for the large cases

---
Tags: string, math, code-challenge, balanced-string, restricted-time
---


# Question
Title: Modular exponentiation using only addition and subtraction
## The challenge

In the least number of source code characters, in a language of your choosing, devise a function which raises base *a* to power *b*, modulo *m*, using purely integer arithmetic, where *a*, *b*, and *m* are all unsigned 64-bit values or larger. You may use signed arithmetic if your language does not have unsigned arithemetic.

This is the standard number-theory operation *a*^*b* (mod m), and not *a*^(*b* mod *m*). Conceptually, and perhaps literally, depending on your implementation, all of your intermediate results should conform to the modulus *m*. That is to say, you won't actually be raising *a* to the *b* power and *then* computing the remainder after dividing by *m* — that would require as much as two trillion gigabytes of RAM to store a number that big. Instead, you'll be raising *a* to the *b* power *while* staying within the constraints of modulus *m*, or straying from it only a bit (no pun intended).

This is actually a lot easier than it sounds!—Raising numbers to astronomically large powers can actually be a surprisingly fast operation. If you do it right, you can compute the result in a handful of microseconds, or perhaps few milliseconds if you're using a slow language. However, you are free to use any algorithm you like, even if it uses an increment-counter in a hard loop running for quadrillions of years. The only requirement with regard to execution time is that your program provably halt in a finite amount of time, providing the correct answer.

## Input assumptions

You can assume that *a* ≥ 0, *b* ≥ 0, m \> 0, and *a* \< *m*, but you should not assume that *b* \< m. That is, you should assume that both *b* and *m* can be any value as large as your integer type supports (this will be 2⁶³–1 for signed 64-bit integers and 2⁶⁴–1 for unsigned 64-bit integers).

If you are given *a* = *b* = 0, you can return whatever value you like, since 0^0 is undefined. Similarly, if you are given m = 0, you can return whatever you like, since 0 is not a valid modulus.

## Test values

Your program should work correctly for all inputs, but here are a few samples to help you with validation:

```
              Base             Exponent               Modulus                Result
                 2                    8                   255                     1
                 2                    8                   256                     0
                 2                    8                   257                   256
                 3                    7                 10000                  2187
                 2                 2046                  2047                     1
               123                  456                   789                   699
                 3                 1000  18446744073709551615  12311760789144243126
             86400             22157322        48519018006822        40149207423504
           8675309         100018327824   8621993634251008000   3858055581225668161
325284989554104320  1508436685178379520   8582294829391072256   6354230931838838784

```

**Counting source characters**

Spaces and tabs each count as 1 character. Newlines do not count, unless the newline character adds syntactic whitespace in order to permit parsing. For example, the newline at the end of the first line here counts as 1 character because it is required to permit proper parsing:

```
#define foo 7
int f(){...}

```

But the newline character at the end of the first line here does not count:

```
int f(){...}
int g(){...}

```

because parsing would still be possible if the two lines were adjoined:

```
int f(){...}int g(){...}

```

This allows you to present your source code with line-breaks at natural locations without penalty, so that you don't have to try to cram everything onto a single line. Finally, if you're using C/C++ and you put a `\` at the end of a line, then the newline also does not count because you're using the `\` only for readability of presentation.

**Restrictions & Allowances:**

1. Arithmetic: You may use only integer addition, subtraction, logical operations, and conditionals. Comparisons count as a form of subtraction. Multiplication and division are not allowed. (However, the specific case of left- and right-shifting may be written using `*2`, `*=2`, `/2`, `/=2` if these are syntactically shorter than the bit-shifting operators in your language, e.g., `<<1`, `<<=1`, `>>1`, `>>=1`, etc.) Use of a built-in exponentiation operator (e.g., `**`) is not allowed.
2. Floating-point arithmetic is not allowed. However, you may use floating-point variables provided you only use them to hold integers. (Floating-point operations aren't really going to help you on this challenge anyway, so don't be discouraged by this restriction.)
3. Your function is not required to have a name (it can be an anonymous or lamba function if your language supports that), but it does have to be a bona fide function that you can call an arbitrary number of times.
4. No global variables. (Exception: If there is no way in your language to provide a solution without global variables, then you may use global variables. But *only* if there is no other way.)
5. You may ignore any and all compiler, interpreter, or runtime warnings, so long as your program computes correct results.
6. If you are using a language which requires importation of type declarations in order to guarantee a 64-bit integer size (e.g, `<stdint.h>` in C), you may assume that this is already included. Note that `uint64_t` is considerably fewer characters than `unsigned long long`.

**Cheating:**

1. You may optionally provide a cheat solution, but only if you are *also* providing a legal solution *and* your cheat solution computes correct results as well (please post the cheat version below the legal version and do not count the cheat version as your score).
2. If you do provide a cheat version that uses a built-in exponentiation operator or function call (e.g., `**` in AWK or `pow()` in C), beware of rounding and truncation issues. Just because you're providing a cheat version doesn't mean you're allowed to produce incorrect results. :-) For example, writing `uint64_t modpow(uint64_t a,uint64_t b,uint64_t m){return pow(a,b)%m;}` in C hasn't even the remotest chance of being correct for anything but the smallest values, so don't do that. (Actually, it might even be a challenge *to* use built-in non-modular exponentiation. I'd be interested to see if anyone actually manages to pull that off. But even though I'm posing that as a sub-challenge, it's still considered a cheat for the purposes of the larger challenge.)

**If you need help getting started:**

Here are a couple resources with simple algorithms for computing modular exponentiation:

1. Modular exponentiation \[Wikipedia.org\]
2. Fastest modular exponentiation \[CodeGolf.StackExchange.com\]

**Lastly:**

I will be posting a solution in C99 that I worked out earlier today as a byproduct of writing a Miller–Rabin primality test for another purpose. My answer should not be treated as an eligible entry to the challenge.

I am really looking forward to seeing what you come up with in Golfscript, Befunge, Haskell, Clojure, and more!

# Answer
> 3 votes
# Python 2 (70)

```
def f(a,b,m,n=1):
 exec("n=0"+"+n"*a+";")*b
 while n>=m:n-=m
 return n

```

Very, very slow. The multiplications are string operations, not arithmetic ones, so I hope they're allowed.

The line with `exec` generates and executes code like (with `a=4`, `b=3`):

```
n=0+n+n+n+n;n=0+n+n+n+n;n=0+n+n+n+n;

```

Edit: Here's two alternative solutions that use list/string multiplication in a cheaper way by representing the current number as a list of ones. They're both exactly the same length as the original (70 chars).

```
def f(a,b,m,s=[1]):
 exec"s*=a;"*b;n=len(s)
 while n>=m:n-=m
 return n

```

```
def f(a,b,m,s=[1]):
 exec"s*=a;"*b
 while s[m:]:s=s[m:]
 return len(s)

```

More edit: A 66-char solution that uses string splitting to do the modulo m

```
def f(a,b,m,s="1"):
 exec"s*=a;"*b
 return len(s.split("1"*m)[-1])

```

and a 65-char recursive one-liner

```
f=lambda a,b,m:b and len((a*f(a,b-1,m)*"1").split("1"*m)[-1])or 1

```

# Answer
> 3 votes
## Haskell (78)(67)(61)

```
p a b m|b==0=1|0<1=until(<m)(+(-m))$sum$replicate a$p a(b-1)m

```

The function f is a simple modulus function implemented using repeated subtraction.

The modular exponentiation function `p` first tries to match `b==0`. If this is true, then it returns 1. Otherwise, it calls `p` recursively, "multiplies" it with `a`, and reduces it `mod m`.

It work with all the inputs until `p 86400 22157322 48519018006822`, where the stack overflows.

**EDIT**: Thank's Matt! Using Matt's idea, I was able to shorten the mod function and have it in place. Still overflows though.

**EDIT**: Realized foldl(+)0 is just a sum. Doh!

# Answer
> 1 votes
## C, 175 characters

Answering my own question. This answer should not be considered an eligible entry to the challenge.

```
#define N uint64_t
#define X(F,G,d)\
N F(N m,N a,N b){N c=d;for(;b;b/=2){if(b&1)c=G(m,c,a);a=G(m,a,a);}return c;}
N A(N m,N a,N b){return a+=b,a-(a<m&&a>=b?0:m);}X(M,A,0)X(E,M,1)

```

***How it works:*** The macro invocation `X(E,M,1)` generates a function `E(m,a,b)`, and the invocation `X(M,A,0)` generates a function `M(m,a,b)` using the same macro template with slightly different parameters. `E(m,a,b)` is the modular Exponentiation function. It calls the modular Multiplication function `M(m,a,b)`, which in turn calls the modular Addition function `A(m,a,b)`. The modular addition function has subtle logic to detect and handle both 64-bit overflow and modular overflow correctly, which is transparently leveraged by the higher-level functions.

***Performance:*** Worst-case performance of this is approximately (log₂*m*)² steps, or about 4096 steps for large 64-bit *m*.

Runtime on a 3.4 GHz Intel Core i7 to compute 1 million different values of

> a ^ 18446744073709551615 (mod 18446744073709551615)

for *a* ∈ \[1,10⁶\] is 51.8 seconds, or 51.8 microseconds per exponentiation invocation, where 18446744073709551615 = 2⁶⁴ – 1, which is the most taxing 64-bit value for this method.

At the other end of the spectrum, using much smaller values, the runtime to compute 1 million different values of

> a ^ a (mod 2a + 1)

for *a* ∈ \[1,10⁶\] is only 3.41 seconds, or 3.41 microseconds per exponentiation operation.

---

## C, 110 characters

Here is formulation using nested loops:

```
#define N uint64_t
N E(N M,N A,N B){N C=1;while(B--){N c=0,a=A;while(a--)c+=C,c>=M||c<C?c-=M:0;C=c;}return C;}

```

***How it works:*** The capital variables A, B, and M are the original values passed in; the lowercase variables c and a are temporary work variable copies of their uppercase counterparts. The inner loop performs repeated addition to produce multiplication. The outer loop performs repeated multiplication (using the inner loop) to produce exponentiation.

***Performance:*** This formulation is reasonably fast for very small input values, but performs extremely poorly for even moderately large values. The runtime is proportional to the product of *a* and *b* and is independent of *m*; in other words, this is an O(*ab*) algorithm. Worst-case performance on 64-bit input is 2¹²⁸ steps, which on my system would require 4.2 × 10²⁹ seconds or about 13 thousand million million million years. For worst-case input, this is 10³⁴ times slower than the more efficient version earlier.

# Answer
> 1 votes
## Javascript (92) 89

```
function f(a,b,m){
    c=1;
    while(b--){
        o=0;
        for(i=0;i<a;i++){
            o+=c-m;
            if(o<0)
                o+=m;
        }
        c=o;
    }
    return c;
}

```

Thanks to Todd for the while loop trick. I didn't know Javascript could do that.

Each iteration through the outer loop "multiplies" the result by a. Essentially it adds the previous iteration's result to itself a times (i.e. multiplying itself by a). It also subtracts m each time, and if it's less than 0, it adds it back.

This function is not very efficient, especially for large inputs, but it should eventually return the correct response.

# Answer
> 1 votes
# Haskell: 87 bytes

Performs modular exponentiation *x**y* mod *n* in a number of operations which is logarithmic in the exponent *y*. The code

```
(x!y)m|odd y=z q|y>0=q|0<1=1where z 0=0;z n=until(<m)(+(-m))$x+z(n-1);q=(z x!div y 2)m

```

defines an operator (!) to do modular exponentiation, so you can use it like

```
(2!3) 5 == 3

```

The program works by using the two relations *x*2 *n* = (*x*2)*n* and *x*2 *n* \+ 1 = *x* (*x*2)*n* to accumulate the result, halving the exponent at each step. Intermediate results are taken mod *m* by repeated subtraction. Here's an ungolfed version:

```
(x ^% y) m
    | y == 0     =  1
    | odd y      =  x `times` (squaredX ^% halfY) m
    | otherwise  =  (squaredX ^% halfY) m
    where squaredX = x `times` x
          halfY = y `div` 2
          a `times` 0 = 0
          a `times` b = reduce $ a + a `times` (b - 1)
          reduce n = if n < m then n else reduce (n - m)

```

*Note:* div is used to carry out a right shift operation only.

---
Tags: code-golf, math, arithmetic, number-theory
---


title: Molar masses of compounds

text:
# Question
Title: Molar masses of compounds
## Task

Write a program that takes in a compound made solely of elements with an atomic number less than or equal to 92 (Uranium), and outputs the molar mass of the compound in `grams/mole`.

## Rules and Restrictions

* You may not use a function that directly calculates molar masses for you.
* Your program must be able to run on an offline machine.
* You MAY use a separate data file. Contents of this file must be provided.
* Your score is the length of your program in bytes, plus the the length of your data file in bytes, should you choose to use one.
* This is , therefore, lowest score wins.

## Input

A string containing the compound. This string may be read through `STDIN`, passed as an argument, or set to a variable (please specify which). The following are all valid inputs:

* `CH2` (one Carbon, two Hydrogens)
* `(CH2)8` (8 Carbons, 16 Hydrogens)
* `U` (1 Uranium)

Your program is not required to function for embedded parentheses (i.e. `((CH3)2N4)4`), nor for any compound that contains an element with atomic number greater than 92. If your program does not function for either of the above two cases, it must output `Invalid formula` for such cases - no undefined behavior.

## Output

You should output, to `STDOUT` or to a variable, the molar mass of the compound in `grams/mole`. A list of atomic masses of elements is available here (Wikipedia). Your answer should be accurate to the decimal place for compounds containing fewer than 100 atoms (rounded).

If the input is invalid, `Invalid formula` must be outputted.

Information on calculating the molar mass of a compound in `grams/mole` (Wikipedia).

## Examples

```
Input                   Output
H2O                     18.015
O                       15.999 (16 acceptable)
C6H2(NO2)3CH3           227.132
FOOF                    69.995
C6H12Op3                Invalid formula
Np                      237 (or Invalid formula)
((C)3)4                 144.132 (or Invalid formula)
CodeGolf                Invalid formula

```

# Answer
# Bash, ~~978 708 675 673 650 636 632 631 598~~ 594

**211 bytes for the program and 382 bytes for the data.**

Input is on STDIN, output is on STDOUT. WARNING: creates files called `g` and `a`, if they exist, they will be overwritten!

```
zcat y>g 2>a
s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`)
p=1.008
v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'`
r=(`tail -1 g`)
for n in {0..91};{
p=`bc<<<$p+${r[n]}`
v=${v//${s[n]}/+$p}
}
o=`bc<<<0$v 2>a`
echo ${o:-Invalid formula}

```

## Data file

This requires a file called `y`, which is the zopfli-compressed form of this data (no trailing newline). zopfli is a gzip-compatible compression algorithm and can be decompressed with standard gzip tools. It was run with 1024 iterations (this is probably too much). The last 8 bytes were then removed.

```
HHeLiBeBCNOFNeNaMgAlSiPSClKArCaScTiVCrMnFeNiCoCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbITeXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcPaThU
0 2.995 2.937 2.072 1.798 1.201 1.996 1.992 2.999 1.182 2.81 1.315 2.677 1.103 2.889 1.086 3.39 3.648 .850 .130 4.878 2.911 3.075 1.054 2.942 .907 2.848 .24 4.613 1.834 4.346 2.904 2.292 4.038 .944 3.894 1.670 2.152 1.286 2.318 1.682 3.054 2.04 3.07 1.836 3.514 1.448 4.543 2.407 3.892 3.050 5.144 .696 3.693 1.612 4.422 1.578 1.211 .792 3.334 .758 5.36 1.604 5.286 1.675 3.575 2.43 2.329 1.675 4.120 1.913 3.523 2.458 2.892 2.367 4.023 1.987 2.867 1.883 3.625 3.788 2.82 1.78 .02 1 12 1 3 1 4.036 1.002 5.991

```

The base64 of `y` is (use `base64 -d` to reproduce the original file):

```
H4sIAAAAAAACAwTB226DMAwA0G9LvEJQIbVi70LfHPBoJAiSaR729zsnBB2LVw/x0UWNMm1up4IE
+90ZCC1cvsCm2mkscEJ71l56dRept7ulTDY/Lebp5CW19MLVbbAOlSrlgfVH4fIyCihaXPGg49b6
lfPHXzhvxsecxxZ+Wb6TPq7B8O1a2HjH7Aue7p1qZ0ncgsKvz/8WxuRGoigGgfcfxYvA8r7kn9iA
ei6ohAt/+lzuihmD1PFnMrdIV0PeNfOczh3Ylrw8hnHaM6w1WC8V3X4hcYjOfbKlTyz0pewsP5nh
plOUK9mkPzkd4HLiCbktIGyQI5uaUvZzNBrwLhOf9hJij+Jo5WBf6mHLfh2OFqeaxOHbaGAZl5mL
h5UBI3Hlx99GX4llPumDjgw+NIee7uCaRbrZkzluIhJYi2E0ZU2gb5OnYBTSJQMRfv91irmCz4KK
B5Va5J7T7IGjHnR22PeAd+m3F3KW/voz4BMFPGNgxHE0Loq65M6+Pw==

```

The md5sum is `d392b0f5516033f2ae0985745f299efd`.

## Explanation

The numbers in the file are increments of relative atomic mass (so the relative atomic mass of lithium is `1.008 + 0 + 2.995 + 2.937`).

This script works by converting the chemical formula into an arithmetical expression with `+` and `*`, replacing each symbol with its relative atomic mass, then feeding the expression to `bc`. If the formula contains invalid symbols, `bc` will give a syntax error and output nothing to STDOUT; in that case, the output is `Invalid formula`.

If STDIN is empty, the output is `0`. Nested brackets are supported.

```
zcat y>g 2>a # Unzip the file y and output result to the file g. Send standard error to file a (there will be an error because the last 8 bytes are missing)
s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`)  # Read from g to sed; append a space after any capital letter optionally followed by a lowercase letter; exit at the end of the first line so the atomic masses are not processed in this way; parse result as space-separated array and save to variable $s
p=1.008 # In the upcoming loop, $p is the value obtained in the previous iteration
v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'` # Read from standard input to sed; prepend a * after any sequence of digits; replace ( with +(0; save to $v
r=(`tail -1 g`) # Get the last line of file g; parse as space-separated array; save to $r
for n in {0..91};{ # Loop once for each number from 0 to 91; set $n to the current number each iteration
p=`bc<<<$p+${r[n]}` # Concatenate $p, + and the next number from $r; send to bc and evaluate as arithmetic expression; save to $p (i.e. add the next increment from the file to $p)
v=${v//${s[n]}/+$p} # Replace every occurence of the current element symbol with + and $p (i.e. replace each symbol with a + and its relative atomic mass
} # end loop
o=`bc<<<0$v 2>a` # Prepend 0 to $v; send to bc and evaluate as arithmetic expression; redirect any errors on standard error to the file a; save result to $o
echo ${o:-Invalid formula} # If $o is empty (if there was a syntax error), output Invalid formula; otherwise output $o

```

## Example

```
C6H2(NO2)3CH3  #input
C*6H*2+(0NO*2)*3CH*3  #after line 3
+12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3  #after the loop in lines 4-6
0+12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3  #given to bc in line 7
227.132 #output as evaluated by bc

```
> 5 votes

# Answer
# Javascript, 1002

Input is in `q` and output is in `a`. I was unsure of what the rules for rounding were, so I truncated to 3 places after the decimal (or fewer, if digits were unavailable from Wikipedia).

```
H=1.008
He=4.002
Li=6.94
Be=9.012
B=10.812
C=12.011
N=14.007
O=15.999
F=18.998
Ne=20.179
Na=22.989
Mg=24.305
Al=26.981
Si=28.085
P=30.973
S=32.06
Cl=35.45
Ar=39.948
K=39.098
Ca=40.078
Sc=44.955
Ti=47.867
V=50.941
Cr=51.996
Mn=54.938
Fe=55.845
Co=58.933
Ni=58.693
Cu=63.546
Zn=65.38
Ga=69.723
Ge=72.630
As=74.921
Se=78.96
Br=79.904
Kr=83.798
Rb=85.467
Sr=87.62
Y=88.905
Zr=91.224
Nb=92.906
Mo=95.96
Tc=98
Ru=101.07
Rh=102.905
Pd=106.42
Ag=107.868
Cd=112.411
In=114.818
Sn=118.710
Sb=121.760
Te=127.60
I=126.904
Xe=131.293
Cs=132.905
Ba=137.327
La=138.905
Ce=140.116
Pr=140.907
Nd=144.242
Pm=145
Sm=150.36
Eu=151.964
Gd=157.25
Tb=158.925
Dy=162.500
Ho=164.930
Er=167.259
Tm=168.934
Yb=173.054
Lu=174.966
Hf=178.49
Ta=180.947
W=183.84
Re=186.207
Os=190.23
Ir=192.217
Pt=195.084
Au=196.966
Hg=200.592
Tl=204.38
Pb=207.2
Bi=208.980
Po=209
At=210
Rn=222
Fr=223
Ra=226
Ac=227
Th=232.038
Pa=231.035
U=238.028
try{a=eval(q.replace(/(\d+)/g,'*$1').replace(/(\w)(?=[A-Z\(])/g,'$1+'))}catch(e){a="Invalid formula"}

```
> 2 votes

# Answer
# Mathematica 9 - ~~247~~ 227

This is clearly cheating as I'm using a function that directly calculates atomatic masses (but not molar masses!):

```
r=StringReplace;f[s_]:=Check[ToExpression@r[r[r[s,x:RegularExpression["[A-Z][a-z]*"]:>"ElementData[\""<>x<>"\",\"AtomicWeight\"]+"],x:DigitCharacter..:>"*"<>x<>"+"],{"+*"->"*","+"~~EndOfString->"","+)"->")"}],"Invalid formula"]

```

Usage: Call the function `f` with a string containing the formula, the output will be the mass.

Test:

```
f["H2O"]           (* => 18.0153 *)
f["O"]             (* => 15.9994 *)
f["C6H2(NO2)3CH3"] (* => 227.131 *)
f["FOOF"]          (* => 69.9956 *)
f["C6H12Op3"]      (* => Invalid formula *)
f["Np"]            (* => 237 *)
f["((C)3)4"]       (* => 144.128 *)
f["CodeGolf"]      (* => Invalid formula *)

```

Mathematica 10 doesn't output a raw number, but a number with a unit, so that may not be acceptable.
> 2 votes

# Answer
# Perl - 924

It uses a series of regex substitution operations on the inputted formula to expand the subscripted elements and groups, replace the elements with atomic weights, and transform it into a sequence of additions which it then evaluates.

```
$_=<>;chop;@g='H1008He4003Li6940Be9012B10810C12011N14007O15999F18998Ne20179Na22989Mg24305Al26981Si28085P30974S32060Cl35450Ar39948K39098Ca40078Sc44955Ti47867V50942Cr51996Mn54938Fe55845Co58933Ni58693Cu63546Zn65380Ga69723Ge72630As74922Se78960Br79904Kr83798Rb85468Sr87620Y88906Zr91224Nb92906Mo95960Tc98Ru101070Rh102906Pd106420Ag107868Cd112411In114818Sn118710Sb121760Te127600I126904Xe131293Cs132905Ba137327La138905Ce140116Pr140907Nd144242Pm145Sm150360Eu151964Gd157250Tb158925Dy162500Ho164930Er167259Tm168934Yb173054Lu174967Hf178490Ta180948W183840Re186207Os190230Ir192217Pt195084Au196967Hg200592Tl204380Pb207200Bi208980Po209At210Rn222Fr223Ra226Ac227Th232038Pa231036U238028'=~/(\D+)([\d\.]+)/g;for$b(0..91){$d=2*$b+1;$g[$d]=$g[$d]>999?$g[$d]/1000:$g[$d]}%h=@g;for$a('(\(((?>[^()]|(?1))*)\))(\d+)','()([A-Z][a-z]?)(\d+)'){for(;s/$a/$2x$3/e;){}}s/([A-Z][a-z]?)/($h{$1}||_).'+'/ge;if(/_/){print'Invalid formula';exit}$_.=0;print eval;

```
> 2 votes

# Answer
## PHP — 793 (583 + 210)

Largely outdistanced by professorfish's answer, who is using a similar method, but hey… The symbols and the masses are gzip-compressed in the file `a` obtained with the following code:

```
$symbolsList = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mg', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U'];
$massesList = [1.008, 4.003, 6.94, 9.012, 10.81, 12.011, 14.007, 15.999, 18.998, 20.18, 22.99, 24.305, 26.982, 28.085, 30.974, 32.06, 35.45, 39.948, 39.098, 40.078, 44.956, 47.867, 50.942, 51.996, 54.938, 55.845, 58.933, 58.6934, 63.546, 65.38, 69.726, 72.630, 74.922, 78.96, 79.904, 83.798, 85.468, 87.62, 88.906, 91.224, 92.906, 95.96, 98, 101.07, 102.906, 106.42, 107.868, 112.411, 114.818, 118.710, 121.760, 127.60, 126.904, 131.293, 132.905, 137.327, 138.905, 140.116, 140.908, 144.242, 145, 150.36, 151.964, 157.25, 158.925, 162.5, 164.93, 167.259, 168.934, 173.054, 174.967, 178.49, 180.948, 183.84, 186.207, 190.23, 192.217, 195.084, 196.967, 200.592, 204.38, 207.2, 208.98, 209, 210, 222, 223, 226, 227, 232.038, 231.036, 238.029];

$fileArrayContent = [$symbolsList, $massesList];
$fileStringContent = json_encode($fileArrayContent);

$file = gzopen('a', 'w9');
gzwrite($file, $fileStringContent);
gzclose($file);

```

The formula should be stored in the `$f` variable:

```
$a=json_decode(gzfile('a')[0]);$r=@eval('return '.str_replace($a[0],$a[1],preg_replace(['#(?<=(?!\().)(\(|'.implode('|',$a[0]).')#','#\d+#'],['+${1}','*$0'],$f)).';');echo error_get_last()?'Invalid formula':$r;

```

Here is the ungolfed and commented version:

```
// Recover the data stored in the compressed file
$fileStringContent = gzfile('a')[0];
$fileArrayContent = json_decode($fileStringContent);
$symbolsList = $fileArrayContent[0];
$massesList = $fileArrayContent[1];

$formula = preg_replace('#(?<=(?!\().)(\(|'. implode('|', $symbolsList) .')#', '+${1}', $formula); // Add a "+" before each opening paranthesis and symbol not at the beginning of the string and not preceded by an opening paranthesis
$formula = preg_replace('#\d+#', '*$0', $formula); // Add a "*" before each number

$formula = str_replace($symbolsList, $massesList, $formula); // Replace each symbol with its corresponding mass

$result = @eval('return '. $formula .';'); // Evaluate the value without showing the errors
echo error_get_last() ? 'Invalid formula' : $result; // Print the value, or "Invalid formula" if there was an error

```
> 1 votes

# Answer
# Javascript (E6) 1231

As a function with the input as argument and returning the output. Precision: 3 decimal digits

Use regexp to transform the chemical formula in a simple arithmethic expression, with sums and products, replacing:

* `(` with `+(`
* any numeric sequence with '\*', then the numeric sequence
* any Capital letter followed by letters with '+', then the atomic mass of the corresponding element (if found)

Then the expression is evaluated and the value returned. In case of errors or if value is NaN (or zero) then function returns 'Invalid formula'

**Now I see that all other answers use the same method ...** oh well here is the javascript version

```
F=f=>{
  T={H:1.008,He:4.002,Li:6.94,Be:9.012,B:10.81,C:12.011
  ,N:14.007,O:15.999,F:18.998,Ne:20.179,Na:22.989,Mg:24.305
  ,Al:26.981,Si:28.085,P:30.973,S:32.06,Cl:35.45,Ar:39.948
  ,K:39.098,Ca:40.078,Sc:44.955,Ti:47.867,V:50.941,Cr:51.996,Mn:54.938
  ,Fe:55.845,Co:58.933,Ni:58.693,Cu:63.546,Zn:65.38,Ga:69.723,Ge:72.630
  ,As:74.921,Se:78.96,Br:79.904,Kr:83.798,Rb:85.467,Sr:87.62,Y:88.905,Zr:91.224
  ,Nb:92.906,Mo:95.96,Tc:98,Ru:101.07,Rh:102.905,Pd:106.42,Ag:107.868,Cd:112.411
  ,In:114.818,Sn:118.710,Sb:121.760,Te:127.60,I:126.904,Xe:131.293
  ,Cs:132.905,Ba:137.327,La:138.905,Ce:140.116,Pr:140.907,Nd:144.242,Pm:145
  ,Sm:150.36,Eu:151.964,Gd:157.25,Tb:158.925,Dy:162.500,Ho:164.930,Er:167.259
  ,Tm:168.934,Yb:173.054,Lu:174.966,Hf:178.49,Ta:180.947,W:183.84,Re:186.207
  ,Os:190.23,Ir:192.217,Pt:195.084,Au:196.966,Hg:200.592,Tl:204.38,Pb:207.2
  ,Bi:208.980,Po:209,At:210,Rn:222,Fr:223,Ra:226,Ac:227,Th:232.038,Pa:231.035
  ,U:238.028,Np:237,Pu:244,Am:243,Cm:247,Bk:247,Cf:251,Es:252,Fm:257,Md:258
  ,No:259,Lr:266,Rf:267,Db:268,Sg:269,Bh:270,Hs:269,Mt:278
  ,Ds:281,Rg:281,Cn:285,Uut:286,Fl:289,Uup:289,Lv:293,Uus:294,Uuo:294};
  e='Invalid formula';
  try{return eval(f.replace(/([A-Z][a-z]*)|(\d+)|(\()/g,(f,a,b,c)=>c?'+(':b?'*'+b:a='+'+T[a]))||e}
  catch(x){}return e
}

```
> 1 votes

# Answer
# Scala, 1077

I see all your solutions in dynamically typed languages with cop-outs like `eval` or built-in atomic mass function and raise you a statically-typed language solution:

```
object M{type S=String;type Z=(Int,S)
val d="H  *dHe JVLi inBe!!rB !5\"C !AiN !W!O !l3F \".*Ne\":_Na\"XUMg\"fUAl#%#Si#0iP #OOS #[&Cl$!,Ar$P|K $GxCa$RBSc%(7Ti%G5V %gwCr%s.Mn&4JFe&>)Co&^yNi&\\ECu'2\"Zn'ERGa'seGe(4^As(M#Se(x Br)$$Kr)MLRb)_5Sr)v,Y *%kZr*>LNb*PBMo*ppTc+(TRu+I4Rh+\\ePd,$,Ag,3RCd,cqIn,}LSn-HrSb-i>Te.IJI .B$Xe.peCs/#sBa/RwLa/ccCe/pXPr/y!Nd0>NPm0FTSm1!VEu12\\Gd1jrTb1|aDy2DdHo2^VEr2wATm3+0Yb3W Lu3k@Hf42nTa4L{W 4kfRe5&wOs5QdIr5fqPt6'BAu6;DHg6azTl7,8Pb7J8Bi7]2Po7]FAt7h$Rn9+bFr96@Ra9V8Ac9`tTh:8NPa:-mU :x4".grouped(5).map{s=>(s.take(2).trim,s(2)*8836+s(3)*94+s(4)-285792)}.toMap
def k(n:S):Z={val x=n.takeWhile(_.isDigit);(if(x=="")1 else x.toInt,n drop x.length)}
def o(m:S):Z={if(m(0)==40){val(i,s)=a(m.tail);if(s(0)!=41)???;val(j,t)=k(s.tail);(j*i,t)}else{val l=if(m.size>1&&m(1).isLower)2 else 1;val(i,s)=d(m.take(l))->m.drop(l);val(j,t)=k(s);(j*i,t)}}
def a(m:S)={var(r,s)=(m,0);do{val(y,z)=o(r);r=z;s+=y}while(r!=""&&r(0)!=41);s->r}
def main(q:Array[S]){println(try{val(m,s)=a(io.Source.stdin.getLines.next);if(s!="")???;m/1e3}catch{case _=>"Invalid formula"})}}

```

I should consider some compression for the data, but for now let's just have the atomic masses in base 94, uncompressed.
> 1 votes

---
Tags: code-golf, math, string, number, chemistry
---


title: Kakuro Combinations

text:
# Question
Title: Kakuro Combinations
## Kakuro Combinations

Because I can't do mental arithmetic, I often struggle with the Kakuro Puzzle, which requires the victim to repeatedly work out which distinct numbers in the range 1 to 9 (inclusive) sum to another number in range 1 to 45 when you know how many numbers there are. For example, if you may want to know how to get 23 from 3 numbers, the only answer is 6 + 8 + 9. (This is the same idea as Killer Sudoku if you are familiar with that).

Sometimes you will have other information, such as that the number 1 *cannot* be present, thus to achieve 8 in just 2 numbers, you can only use 2 + 6 and 3 + 5 (you can't use 4 + 4, because they are not distinct). Alternatively, it may be that you have already found a 3 in the solution, and so something like 19 in 3 numbers must be 3 + 7 + 9.

Your task is to write a program that lists all the possible solutions to a given problem, in a strict order, in a strict layout.

### Input

Your solution can receive the inputs as a *single ASCII string* either through stdin, a command line argument, an argument to a function, a value left on the stack, or whatever madness your favourite esoteric language employs. The string is in the form

```
number_to_achieve number_of_numbers_required list_of_rejected_numbers list_of_required_numbers

```

The first 2 arguments are typical base-10 non-negative non-zero integers in the ranges 1 to 45 and 1 to 9 respectively (using a decimal point would be invalid input), the two lists are just digits strung together with no delimitation in no particular order without repetition, or '0' if they are empty lists. There can be no shared digits between the lists (except for 0). The delimiters are single spaces.

### Output

Your output must start with a line that contains the number of possible solutions. Your program must print out line-break delimited solutions sorted by each increasingly significant digit, where each digit is placed at the position it would be if you listed the numbers from 1 to 9. The examples below will hopefully make this clearer.

If an invalid input is provided I do not care what your program does, though I'd rather it didn't zero my boot sector.

### Examples

For this example input

```
19 3 0 0

```

The expected output would be

```
5
 2     89
  3   7 9
   4 6  9
   4  78
    56 8

```

Note the spaces in place of each "missing" number, these are required; I'm not bothered about spaces which don't have a number after them (such as the missing 9s above). You can assume that whatever you are printing to will use a mono-space font. Note also the ordering, whereby solutions with a smaller smallest digit are listed first, and then those with a smallest next smallest digit, etc.

Another example, based on that above

```
19 3 57 9

```

The expected output would be

```
2
 2     89
   4 6  9

```

Note that every result contains a 9, and no result contains a 5 or 7.

If there are no solutions, for example

```
20 2 0 0

```

Then you should just output a single line with a 0 on it.

```
0

```

I've intentionally made the parsing of the input part of the fun of this question. This is code-golf, may the shortest solution win.

# Answer
### GolfScript, 88 characters

```
~[[]]10,:T{{1$+}+%}/\{\0+`-!}+,\{0`+\`&!}+,\{\,=}+,\{\{+}*=}+,.,n@{1T>''*T@-{`/' '*}/n}/

```

A straight-forward implementation in GolfScript. Takes input from STDIN or stack.

The code can be tested here.

*Code with some comments:*

```
### evaluate the input string
~

### build all possible combinations of 0...9
[[]]              # start with set of empty combination
10,:T             #
{                 # for 0..9
  {1$+}+%         #   copy each item of set and append current digit to this copy
}/                # end for

### only keep combination which the digits given as last argument (minus 0)
\{                # start of filter block
  \0+`            #   add zero to combination and make string out of it
  -!              #   subtract from last argument -> check argument contains any
                  #     excess characters
}+,               # end of filter block

### remove any combination which contains either 0 or any digit from 2nd last argument
\{                # start of filter block
  0`+             #   take argument and append 0
  \`              #   stringify combination
  &!              #   check if no characters are common
}+,               # end of filter block

### filter for correct length
\{                # start of filter block
  \,              #   calc length of combination
  =               #   check if equal to second argument
}+,               # end of filter block

### filter for correct sum
\{                # start of filter block
  \{+}*           #   sum all digits of combination
  =               #   compare with first argument
}+,               # end of filter block

### output
.,                # determine size of set
n                 # append newline
@{                # for each combination in set
  1T>''*          #   generate "123456789"
  T@-             #   generate anti-set of current combination
  {`/' '*}/       #   replace (in the string) each digit within the
                  #   anti-combination with a space characters
  n               #   append newline
}/                # end for

```
> 5 votes

# Answer
# JavaScript (E6) 172 ~~180 275 296~~

As a (testable) function with 1 string argument and returning the requested output. To have a real output change return with alert(), same byte count, but beware, the alert font is not monospace.

```
F=i=>{
  [t,d,f,m]=i.split(' ');
  for(l=0,r='',k=512;--k;!z&!h&!o&&(++l,r+=n))
    for(z=n='\n',h=d,o=t,b=i=1;i<=9;b+=b)
      z-=~(b&k?(--h,o-=i,n+=i,f):(n+=' ',m)).search(i++);
  return l+r
}

```

**Test** In FireFox or FireBug console

```
console.log(['19 3 0 0','19 3 57 9','19 3 57 4','20 2 0 0'].map(x=>'\n'+x+'\n' +F(x)).join('\n'))

```

Test output:

```
19 3 0 0
5
 2     89
  3   7 9
   4 6  9
   4  78
    56 8

19 3 57 9
2
 2     89
   4 6  9

19 3 57 4
1
   4 6  9

20 2 0 0
0

```

**Ungolfed**

```
F=i=>{
  [target, digits, forbidden, mandatory]=i.split(' ')

  result = '', nsol=0
  for (mask = 0b1000000000; --mask > 0;)
  {
    cdigits = digits
    ctarget = target
    bit = 1
    numbers = ''
    for (digit = 9; digit > 0; bit += bit, digit--)
    {

      if (bit & mask)
      {
        if (forbidden.search(digit)>=0) break;
        cdigits--;
        ctarget -= digit;
        numbers = digit + numbers;
      }
      else
      {
        if (mandatory.search(digit)>=0) break;
        numbers = ' '+numbers;
      }
    }
    if (ctarget==0 && cdigits == 0)
    {
        result += '\n'+numbers
        nsol++
    }
  }
  return nsol + result
}

```
> 6 votes

# Answer
## Mathematica, 239 bytes

(I admit I started working on this while it was still in the sandbox.)

```
{t,n,a,b}=FromDigits/@StringSplit@i;Riffle[c=Cases[Union/@IntegerPartitions[t,n,Complement[r=Range@9,(d=IntegerDigits)@a]],k_/;(l=Length)@k==n&&(b==0||l[k⋂d@b]>0)];{(s=ToString)@l@c}~Join~((m=#;If[m~MemberQ~#,s@#," "]&/@r)&/@c),"\n"]<>""

```

Ungolfed

```
{t, n, a, b} = FromDigits /@ StringSplit@i;
Riffle[
  c = Cases[
    Union /@ IntegerPartitions[
      t, n, Complement[r = Range@9, (d = IntegerDigits)@a
       ]
      ],
    k_ /; (l = Length)@k ==
       n && (b == 0 || l[k ⋂ d@b] > 0)
    ];
  {(s = ToString)@l@c}~
   Join~((m = #; If[m~MemberQ~#, s@#, " "] & /@ r) & /@ c),
  "\n"] <> ""

```

It expects the input string to be stored in `i`.

It's fairly straightforward. First, input parsing. Then I use `IntegerPartitions` to figure out how I can split up the first number into the allowed numbers. Then I filter out all partitions that use duplicates or don't contain required numbers. And then for each solution I create a list from `1` to `9` and convert the present numbers into their string representation and the others into spaces. And then I concatenate everything.
> 4 votes

# Answer
## Groovy - 494 chars

Large, uninspired answer, but it uses Google Guava to generate the "power set".

Golfed:

```
@Grab(group='com.google.guava', module='guava', version='17.0')
m=(args.join(" ")=~/(\d+) (\d+) (\d+) (\d+)/)[0]
i={it as int}
n=i(m[1])
r=i(m[2])
j=[]
m[3].each{if(i(it))j<<i(it)}
q=[]
m[4].each{if(i(it))q<<i(it)}
d=1..9 as Set<Integer>
t=[]
com.google.common.collect.Sets.powerSet(d).each{x->
if(x.sum()==n&&x.size()==r&&x.disjoint(j)&&x.containsAll(q)) {
s="";for(i in 0..8){if(x.contains(i+1)){s+=(i+1) as String}else{s+=" "}};t<<s}
}
p={println it}
p t.size()
t.sort().reverse().each{p it}

```

Sample runs:

```
$ groovy K.groovy 19 3 0 0
5
 2     89
  3   7 9
   4 6  9
   4  78
    56 8
$ groovy K.groovy 19 3 5 0
4
 2     89
  3   7 9
   4 6  9
   4  78
$ groovy K.groovy 19 3 5 9
3
 2     89
  3   7 9
   4 6  9
$ groovy K.groovy 20 2 0 0
0

```

Ungolfed:

```
@Grab(group='com.google.guava', module='guava', version='17.0')

m=(args.join(" ")=~/(\d+) (\d+) (\d+) (\d+)/)[0]
i={it as int}
n=i(m[1])
r=i(m[2])

j=[]
m[3].each{if(i(it))j<<i(it)}
q=[]
m[4].each{if(i(it))q<<i(it)}

d=1..9 as Set<Integer>
t=[]

com.google.common.collect.Sets.powerSet(d).each{ x ->
    if(x.sum()==n && x.size()==r && x.disjoint(j) && x.containsAll(q)) {
        s=""
        for(i in 0..8) {
            if(x.contains(i+1)){s+=(i+1) as String}else{s+=" "}
        }
        t<<s
    }
}

p={println it}
p t.size()
t.sort().reverse().each{p it}

```
> 1 votes

---
Tags: code-golf, arithmetic
---