This problem was pretty straight forward. I started by creating the function that concatenates the numbers by the given formula. I tested this against the example given in the problem. From there I tested out a couple more numbers, one large and one small. I wanted to see if the function was strictly increasing, meaning that when he input gets larger, so does the output. This was indeed the case, which meant I could use a binary search to find the ultimate solution.
Only challenge here was in comparing numbers at such high precision after the decimal point. I used the python decimal package for this. Though often slow, the decimal package worked in this case because it only took 80 iterations to find the solution. Runs in about 180 milliseconds.
import decimal as d
rnd = 24
d.getcontext().prec = rnd + 4
def concat(theta):
numstr, b1 = '', theta
while len(numstr) < rnd + 3:
b2 = int(b1) * (b1 - int(b1) + 1)
numstr += str(int(b1))
b1 = b2
return numstr[:1] + '.' + numstr[1:rnd+1]
def solve():
mins, maxs, two = d.Decimal(2), d.Decimal(3), d.Decimal(2)
while True:
theta = (mins + maxs) / two
thetas = str(theta)[:rnd+2]
tau = concat(theta)
if tau == thetas:
return tau
elif tau > thetas:
mins = theta
else:
maxs = theta
if __name__ == '__main__':
print(solve())
import pytest
from problem import concat
_test_concat = (
(2.0, '2.222222222222222222222222'),
(2.956938891377988, '2.358132134558914423337759'),
(2.99, '2.359151928424242424242446'),
)
@pytest.mark.parametrize('n,expect', _test_concat)
def test_concat(n, expect):
assert expect == concat(n)