Smallest Good Base in Python

Finding the smallest good base is a mathematical problem where we need to find the smallest base k ? 2 such that all digits of number n in base k are 1. For example, 121 in base 3 is 11111, so 3 is a good base for 121.

Understanding the Problem

If a number n has all digits as 1 in base k with m digits, then:

n = 1 + k + k² + k³ + ... + k^(m-1) = (k^m - 1) / (k - 1)

We need to find the smallest k ? 2 that satisfies this equation for some valid m.

Algorithm Approach

The solution uses binary search to find the base for each possible number of digits:

  1. getSum() - Calculates the sum 1 + k + k² + ... + k^(length-1)
  2. check() - Uses binary search to find base k for given digit length
  3. smallestGoodBase() - Iterates through possible digit lengths to find smallest base

Implementation

class Solution:
    def getSum(self, base, length):
        """Calculate sum: 1 + base + base^2 + ... + base^(length-1)"""
        total = 0
        power = 1
        for i in range(length):
            total += power
            power *= base
        return total
    
    def check(self, n, length):
        """Binary search for base that gives sum equal to n"""
        low = 2  # minimum valid base
        high = n
        
        while low <= high:
            mid = low + (high - low) // 2
            total = self.getSum(mid, length)
            
            if total == n:
                return mid
            elif total > n:
                high = mid - 1
            else:
                low = mid + 1
        return -1
    
    def smallestGoodBase(self, n):
        """Find smallest good base for number n"""
        n = int(n)
        
        # Try from maximum possible digits down to 2
        # Maximum digits is log_2(n) + 1
        for length in range(64, 1, -1):
            base = self.check(n, length)
            if base >= 2:
                return str(base)
        
        # If no base found, return n-1 (always works for 2 digits: 11 in base n-1)
        return str(n - 1)

# Test the solution
solution = Solution()
print("Input: '121'")
print("Output:", solution.smallestGoodBase("121"))
print()

print("Input: '13'") 
print("Output:", solution.smallestGoodBase("13"))
Input: '121'
Output: 3

Input: '13'
Output: 3

How It Works

For n = 121:

  • Try length = 5: Need base k where 1+k+k²+k³+k? = 121
  • Binary search finds k = 3: 1+3+9+27+81 = 121 ?
  • So 121 = 11111 in base 3

Key Points

  • We search from maximum possible digits down to find the smallest base
  • Binary search efficiently finds the exact base for each digit length
  • If no base is found, n-1 always works (gives "11" in base n-1)
  • Time complexity: O(log²n) due to binary search within digit iteration

Conclusion

The smallest good base problem combines mathematical insight with binary search optimization. The key is recognizing that we need to check all possible digit lengths and use binary search to find the corresponding base efficiently.

Updated on: 2026-03-25T08:41:37+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements