Your task is, given x
, output 2*x
. Easy right!? But there's a catch: x
will be given as a (possibly infinite) continued fraction, and the output must be a continued fraction. The input is guaranteed to be a real algebraic number whose degree is at most 2.
Input: The continued fraction of x
. This is split into 3 parts: the integer part, the prefix, and the repeating part. The integer part consists of a single integer. The prefix and repeating part are (possibly empty) arrays of positive integers which describe the prefix and repeating part of the continued fraction. For example, the input (3, [1], [2, 4])
represents the continued fraction [3; 1, 2, 4, 2, 4, ...]
.
If the repeating part is empty, that indicates a rational number. For example, (3, [1, 2], [])
represents [3; 1, 2] = 11/3
. You must accept both forms of a rational number (i.e. (3, [1, 1, 1], [])
, which is [3; 1, 1, 1] = 11/3
should also be valid input).
Output: Output the continued fraction of twice the input, in the same format as the input. If the output is rational, you may output either form of the continued fraction. As long as the answer is equivalent to the correct answer, it is fine; no "compression" is necessary, so the infinite part might be "unrolled" a little (e.g. [1; 4, 2, 3, 2, 3...]
may be written (1, [4], [2, 3])
or (1, [4, 2, 3], [2, 3])
). All answers must be exact.
Test cases: The exact form column is given for convenience.
Input Exact Form Output
(0, [] []) 0 (0, [] []) or (-1, [1], [])
(-5, [1, 1], []) -4.5 (-9, [], []) or (-10, [1], [])
(3, [1, 2], []) 11/3 (7, [3], []) or (7, [2, 1], [])
(1, [], [2]) sqrt(2) (2, [], [1, 4])
(-1, [2], [2, 1]) -1/sqrt(3) (-2, [1, 5], [2, 6])
And finally a slightly larger test case to ensure precision: (0, [1], [6, 1, 3, 1, 42, 1, 3, 1, 6, 2]) --> (1, [], [1, 2, 1, 8, 1, 20, 1, 8, 1, 2, 1, 2])
.
Shortest code wins!
Hint: You can perform arithmetic in a rather straightforward manner on continued fractions as described here. Doubling a continued fraction is just a special case of this algorithm (although the tricky part may be to find when the continued fraction repeats).
Sqrt[2]
. \$\endgroup\$[3; 1, 1, 1]
would be(3, [1, 1, 1], [])
in the input format we're using - so the question should probably mention it in that format (in the third paragraph), just to ensure clarity. \$\endgroup\$(-2, [1, 5, 2], [6, 2])
be acceptable output for input(-1, [2], [2, 1])
? How about(-2, [1, 5, 2, 6, 2, 6], [2, 6])
? \$\endgroup\$