Kaosar and Minimization#12437

Kaosar and Minimization (Editorial)

Problem Author:

Al_Kaosar

Prepared by:

MathModel

Edited by:

MathModel

Solution

The objective is to minimize f(x, y) = |n - x^y| + |x - y| for x, y \ge 1.

For a fixed , the value of that makes x^y closest to is either \lfloor n^{1/y} \rfloor or \lceil n^{1/y} \rceil. Since n \le 10^{18}, if x \ge 2, then can be at most because 2^{60} > 10^{18}. If x=1, the expression becomes |n-1| + |1-y|, which is minimized at y=1, yielding n-1.

We can iterate through all possible values of from to . For each , we estimate x \approx n^{1/y}. Due to potential floating-point precision issues with n=10^{18}, it is safer to find using pow(n, 1/y) and then check a small range around it, or use binary search to find such that x^y \le n.

For each y \in [1, 62], we test x_{cand} \in \{\lfloor n^{1/y} \rfloor, \lceil n^{1/y} \rceil\}. We also check x=y as a candidate, as it nullifies the second term of the expression.

The total complexity is O(\log n).

def solve():
 n=int(input())
 ans=n-1
 K=n.bit_length()
 for y in range(2,K+1):
  r=int(n**(1/y))
  for x in(r,r+1):
   if x>0:
    p=pow(x,y)
    ans=min(ans,abs(n-p)+abs(x-y))
 print(ans)

for _ in range(int(input())):
 solve()