1811. Mirror Bases Census
A number lover writes the same integer n in every positional base b with 2 <= b <= n - 1 and wonders in how many of them the digit string reads the same forwards and backwards (a palindrome). For instance, 9 is 1001 in base 2 and 11 in base 8.
Return the number of bases b in that range in which the representation of n is a palindrome. Each base is counted once, and the answer fits easily in an int. Converting n in every base is far too slow for large n: bases up to about the square root of n can be converted directly, while for larger bases the number has only two digits, so a short number-theory argument about divisors of n settles all of them. The intended solution runs in O(sqrt(n)) time with O(1) extra space.
Example 1
- Input:
- n = 9
- Output:
- 2
- Explanation:
9 is 1001 in base 2 and 11 in base 8, both palindromes; bases 3 to 7 give 100, 21, 14, 13 and 12.
Example 2
- Input:
- n = 10
- Output:
- 3
- Explanation:
10 is 101 in base 3, 22 in base 4 and 11 in base 9, so three bases qualify.
Example 3
- Input:
- n = 3
- Output:
- 1
- Explanation:
The only base is 2, where 3 is written 11, so the answer is 1.
Constraints
3 ≤ n ≤ 1010
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(sqrt(n))
- Space
- O(1)