Count bases which contains a set bit as the Most Significant Bit in the representation of N
Given a positive integer N, the task is to count the number of different bases in which, when N is represented, the most significant bit of N is a found to be a set bit.
Input: N = 6
Explanation: The number 6 can be represented in 5 different bases, i.e. base 2, base 3, base 4, base 5, base 6.
- (6)10 in base 2: (110)2
- (6)10 in base 3: (20)3
- (6)10 in base 4: (12)4
- (6)10 in base 5: (11)5
- (6)10 in base 6: (10)6
The base representation for (6)10 in base 2, base 4, base 5, base 6 starts with 1. Hence, the required count of bases is 4.
Input: N = 5
Approach: The given problem can be solved by finding the MSB of the given number N for every possible base and count those bases that have MSB as 1. Follow the steps below to solve the problem:
- Initialize a variable, say count as 0, to store the required result.
- Iterate over the range [2, N] using a variable, say B, and perform the following steps:
- Store the highest power of base B required to represent number N in a variable P. This can be easily achieved by finding the value of (log N to the base B) i.e., logB(N) truncated to the nearest integer.
- To find the value of logB(N) use the log property: logB(N) = log(N)/log(B)
- Store the most significant digit of N by dividing N by (B)P. If it is equal to 1, then increment the value of the count by 1.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)