1503. Repunit Bases

Hard7.5 points estimatedBinary SearchMathsNumber Theory

A museum labels its exhibits with a single whole number n, and a curator likes to rewrite that label in different number systems. A system with base b (where b >= 2) writes n with ordinary positional digits. A label is called a repunit in base b when it needs at least three digits and every digit equals 1, that is n = 1 + b + b^2 + ... + b^(L-1) for some length L >= 3.

Return how many different bases b >= 2 turn n into a repunit. A base can match at most one length, so each base is counted once. For a fixed length the sum grows with the base, so you can binary search the base for each length; guard every multiplication so no intermediate value exceeds n and nothing overflows. The answer is a small non-negative count, and 0 is returned when no base works. Aim for O(log^2 n) time and O(1) extra space.

Example 1

Input:
n = 13
Output:
1
Explanation:

13 is 111 in base 3 and has no other all-ones form with three or more digits, so the count is 1.

Example 2

Input:
n = 31
Output:
2
Explanation:

31 is 11111 in base 2 and 111 in base 5, giving two bases.

Example 3

Input:
n = 10
Output:
0
Explanation:

10 is not a repunit with three or more digits in any base, so the answer is 0.

Constraints

1 ≤ n ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log^2 n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…