P12968 [CCO 2025] Balanced Integer

Background

**Abusing judging resources leads to an account ban.** You can self-test the first three test cases of each Subtask at the link: https://www.luogu.com.cn/problem/U576602 to avoid long judging wait times.

Description

Since the CCO often uses integers, Alice needs to learn about the integers! A positive integer $n$ can be written in base $b$ as the sequence $d_{m-1}d_{m-2} \ldots d_{1}d_{0}$ if the following hold: - Each digit $d_{i}$ is between 0 and $b-1$, inclusive. - $d_{m-1}>0$. - $n=d_{m-1} \times b^{m-1}+d_{m-2} \times b^{m-2}+\cdots+d_{1} \times b^{1}+d_{0} \times b^{0}$. For example, the integer 2025 in base 19 is the sequence $(5,11,11)$ because $2025=5 \times 19^{2}+11 \times 19^{1}+11 \times 19^{0}$. An integer $n$ is $b$-balanced if, when $n$ is written in base $b$, the average of the digits is $\frac{b-1}{2}$. For example, 2025 is 19-balanced because $\frac{5+11+11}{3}=9=\frac{19-1}{2}$. Alice can easily find integers that are 19-balanced. However, she has trouble finding integers that are balanced in multiple ways. Given $B$ and $N$, please help Alice find the minimum integer $x$ such that: - $x$ is $b$-balanced, for all $2 \leq b \leq B$. - $x \geq N$.

Input Format

The first line of input contains two space-separated integers $B$ and $N$ ($N \geq 1$). It is guaranteed that the answer does not exceed $10^{18}$.

Output Format

Output the minimum integer $x$ from the problem statement.

Explanation/Hint

**Sample 1 Explanation** $141$ in base $2$ is $10001101$. The average digit is $$\frac{1+0+0+0+1+1+0+1}{8}=0.5=\frac{2-1}{2}.$$ Therefore, $141$ is 2-balanced. $141$ in base 3 is $12020$. The average digit is $$\frac{1+2+0+2+0}{5}=1=\frac{3-1}{2}.$$ Therefore, $141$ is 3-balanced. $141$ in base 4 is $2031$. The average digit is $$\frac{2+0+3+1}{4}=1.5=\frac{4-1}{2}.$$ Therefore, $141$ is 4-balanced. Lastly, $141 \geq 100$. Feel free to use these code snippets as part of your solution. ```cpp // Important: If x is 0, the result is undefined. int base_2_length(unsigned long long x) { return 64-__builtin_clzll(x); } int base_2_sum(unsigned long long x) { return __builtin_popcountll(x); } ``` The following table shows how the available $25$ marks are distributed: | Marks Awarded | Bounds on $B$ | Bounds on $N$ | | :---: | :---: | :---: | | 2 marks | $2 \leq B \leq 7$ | $1 \leq N \leq 10^{4}$ | | 6 marks | $2 \leq B \leq 6$ | $N = 10^{10}$ | | 2 marks | $2 \leq B \leq 7$ | None | | 9 marks | $8 \leq B \leq 11$ | $N = 1$ | | 4 marks | $B = 8$ | None | | 2 marks | $9 \leq B \leq 11$ | None |