X+Y=Z - but in which base?
Jelly, 16 11 7 bytes
_/N,‘FṀ
This approach is heavily based on @beaker's Octave answer.
Input format is Z, Y, X, with little-endian digit order, using the digit 0 for unary.
Try it online! or run all test cases.
How it works
Rather than incrementally testing potential bases, this solves the polynomial that corresponds to the array P := X + Y - Z. This returns either the largest coefficient of P ≠ 0 – which has to be a root, since there is at least one valid base – or the highest digit of X, Y and Z, incremented by 1.
_/N,‘FṀ Main link. Argument: [Z, Y, X]
_/ Reduce by subtraction; yield Z - X - Y.
This works since Z must have at least as many digits as X and Y.
N Negate to yield X + Y - Z.
‘ Yield [Z, Y, X], with all digits increments by 1.
, Pair the results to the left and to the right.
F Flatten the resulting, nested list.
Ṁ Compute the maximum.
Pyth, 13 bytes
f!-FiRTQheSsQ
Expects Z, followed by X and Y.
Test suite
Essentially, we test every possible base, starting at one more than the largest digit. The test is that we convert each number to the base in question, then fold subtraction over the numbers, and logically negate the result.
Octave, 67 75 38 32 bytes
Because "loop over ALL the things" is too much work.
@(x,y,z)max([m=max(x+y-z) z])+~m
Requires 0 padding to make the input arrays the same size, e.g.:
[2, 158],[88],[3, 12]
becomes
[2, 158],[0, 88],[3, 12]
Since 0
is used for padding, 1
is used as the token for unary.
(Thanks to @DenkerAffe for clarification in the question.)
Sample run on ideone.
Short Explanation:
Take a case involving no carries:
[ 8, 199]
+ [ 1, 34]
-------------
9, 233
- [ 9, 233]
-------------
0, 0 --- no carries
In this case there are no restrictions on base as long as it's greater than any "digit". Simply take the max element of z
(as z >= x,y
) and add 1 (or any positive integer).
In the case of a carry-out (with no carry-in), we've exceeded the base in one of the columns and the difference between x+y
and z
is the base:
[ 2, 140]
+ [21, 183]
--------------
23, 323
- [24, 100]
-------------
-1 223
^ ^------ base
|---------- carry in
If the second column's sum also exceeded the base, requiring a carry-out as well as the carry-in, its value would be base+(-1)
. We will have had a column somewhere to the right with a carry-out and no carry-in that has the correct (greater) base value.