Search code examples
pythonrangemultiplicationradix

Base multiplier


Hello I'm having some trouble with my code to multiply a number to any base from 2 to 9. I have looked online but nothing has the answer I'm looking for. The code I have right now is:

def conver(n,b):
for i in range (b):
    x = b**i 

What I'm wondering is how do I get b to get multiplied by all the values of i, also I know that I'm supposed to incorporate these pieces of code too, but I am not sure how:

n//b + n%b

Solution

  • Here's a version that will work to base 36:

    def conver(n,b):
      assert 1 < b <= 36,'Invalid base. Must be between 2 and 36'
      if n == 0: return '0'
      ans = ''
      while n > 0:
        ans = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n%b] + ans
        n //= b
      return ans
    
    NUMBER = 65535
    for b in range(2,37):
      print(NUMBER,'in base',b,'is',conver(NUMBER,b))