Smallest Good Base in Python


Suppose we have an integer n, we call k >= 2 as a good base of n, when all digits of n base k are 1. So if the number n is given as string, we have to return smallest good base of n as string. So if the number is say 121, then the answer will be 3, as 121 in base 3 is 11111.

To solve this, we will follow these steps −

  • Define a method called getSum(), this will take x and length
  • set mainSum := 0 and temp := 1
  • for i in range 0 to length – 1 −
    • mainSum := mainSum + temp, temp := temp * x
  • return mainSum
  • Define a method called check(), this will take n and length −
  • low := 1, high := n
  • while high >= low −
    • mid := low + (high – low) / 2
    • mainSum := getSum(mid, length)
    • if mainSum = n, then return mid
    • otherwise when mainSum > n, then high := mid – 1
    • otherwise low := mid + 1
  • return -1
  • From the main method do the following −
  • n := the given number
  • for i in range 64 down to 0
    • x := check(n, i)
    • if x >= 2, then return x as string
  • return n – 1 as string

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def getSum(self, x, length):
      mainSum = 0
      temp = 1
      for i in range(length):
         mainSum += temp
         temp *= x
      return mainSum
   def check(self, n, length):
      low = 1
      high = n
      while high >= low:
      mid = low + (high - low) // 2
      mainSum = self.getSum(mid, length)
      if mainSum == n:
         return mid
      elif mainSum > n:
         high = mid - 1
      else:
         low = mid + 1
      return -1
   def smallestGoodBase(self, n):
      n = int(n)
      for i in range(64, 0, - 1):
         x = self.check(n, i)
      if x >= 2:
         return str(x)
      return str(n - 1)
ob = Solution()
print(ob.smallestGoodBase("121"))

Input

“121”

Output

3

Updated on: 01-Jun-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements