Given an integer n represented as a string, return the smallest good base ofn.
We call k >= 2 a good base of n, if all digits of n base k are 1's.
Example 1:
Input: n = "13"
Output: "3"
Explanation: 13 base 3 is 111.
Example 2:
Input: n = "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.
Example 3:
Input: n = "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.
Constraints:
n is an integer in the range [3, 1018].
n does not contain any leading zeros.
Solutions
Solution 1
Thinking
The smallest base \(k\ge 2\) in which \(n\) is all ones. \(k=n-1\) always works (\(11_k\)), but \(n\) can be \(10^{18}\), so scanning \(k\) is impossible.
The number of ones \(m+1\) satisfies \(m<60\). Try \(m\) from large to small and binary-search \(k\) so that \(1+k+\cdots+k^m=n\). A larger \(m\) yields a smaller \(k\), so going downward finds the smallest base first.
The geometric sum is monotone in \(k\), so the binary search is valid. If none hits, fall back to \(n-1\).