Base b Representation

We write a program to find the digits in the base b representation of a positive
integer. The problem is easy, because the lowest digit when n is represented in
base b is the remainder when n is divided by b, and the higher order digits form the
quotient. Hence we can write the following procedure that returns a list of the base b
digits.

In[1]:=

  basebdigits[n_,b_]:= Module[ { m=n, l={}},
                           l= { Mod[ m,b]};
                           m=Quotient[n,b];
                           While[m>0,
                               PrependTo[ l, Mod[m,b]];
                               m=Quotient[m,b];
                                ];
                           Return[l]];

In[2]:=

  basebdigits[ 137,10]

Out[2]

In[3]:=

  basebdigits[ 137,2]

Out[3]

The first argument of Module is a list of variables used in the procedure. In this case, we use
m and l (for the list of digits). The variables can be initialized in the first argument of Module, i.e.
within the braces. The program can also be written recursively because we are
computing the basebdigits of the quotient in the While loop. Here is another program that
computes the base b digit expansion, this time, by calling itself with a smaller argument.

In[4]:=

  newbasebdigits[n_,b_]:= Module[ {m=n, res= { Mod[n,b]}},
                     m= Quotient[ m,b];
                     If[ m>0,
                        res=Join[newbasebdigits[m,b],res]];
                     Return[res]]

In[5]:=

  newbasebdigits[137,2]

Out[5]

Instead of having the output as a list of digits, we may prefer to have it in the standard
representation as a string, that is, 10001001 instead of { 1,0,0,0,1,0,0,1}. This can
be done using the ToString command of Mathematica that will give the string form of
an object, in this case, a string. We convert each digit to a String form and then join
them using the StringJoin command. A list of String related commands is given in the next
section.

In[6]:=

  basebform[n_,b_]:= StringJoin[ 
                         Map[ ToString[ #] &,
                              basebdigits[n,b]]]

In[7]:=

  basebform[ 137,2]

Out[7]

Exercise: Write a program to take the string form of a number and return its value
The Mathematica function Characters will return a list of characters and the command
ToExpression will give the value of the string form of a digit.

Up to Procedural Programming